package org.nmgyjt.springboot.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nimbusds.jose.JOSEException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.nmgyjt.springboot.beans.admin.*;
import org.nmgyjt.springboot.entity.admin.*;
import org.nmgyjt.springboot.entity.area.Area;
import org.nmgyjt.springboot.entity.exception.BizException;
import org.nmgyjt.springboot.entity.protectTarget.ProtectTargetInfo;
import org.nmgyjt.springboot.entity.refuge.RefugeInfo;
import org.nmgyjt.springboot.entity.rescueTeam.RescueTeam;
import org.nmgyjt.springboot.entity.storeInfo.StoreInfo;
import org.nmgyjt.springboot.mapper.CsSystemDeptMapper;
import org.nmgyjt.springboot.mapper.EquipageMapper;
import org.nmgyjt.springboot.mapper.MaterialsMapper;
import org.nmgyjt.springboot.service.*;
import org.nmgyjt.springboot.utils.HttpUtils;
import org.nmgyjt.springboot.utils.IDAASUserUtils;
import org.nmgyjt.springboot.utils.NMGYJTIDAASTokenUtils;
import org.nmgyjt.springboot.utils.upload.SnowflakeIdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.text.ParseException;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2023-07-05
 */
@Service
@Slf4j
public class CsSystemDeptServiceImpl extends ServiceImpl<CsSystemDeptMapper, CsSystemDept> implements ICsSystemDeptService {


    @Autowired
    IIdaasAreaService idaasAreaService;

    @Autowired
    IAreaService areaService;

    @Autowired
    CsSystemAdminServiceImpl adminService;

    @Autowired
    CsSystemDeptServiceImpl deptService;

    @Autowired
    ICsSystemAdminService service;

    @Autowired
    ICsSystemSourceTypeService sourceService;

    @Autowired
    ICsSystemAdminMenuRelService menuRelService;

    @Autowired
    ICsSystemSourceExtService csSystemSourceExtService;

    @Autowired
    private ICsSystemUserService userService;
    @Autowired
    ICsSystemSourcePreSetInfoService preSetInfoService;

    @Autowired
    ICsSystemSourceTypeService iCsSystemSourceTypeService;

    @Autowired
    private IdaasService idaasService;

    @Autowired
    private RescueTeamService rescueTeamService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private ProtectTargetService protectTargetService;
    @Autowired
    private RefugeService refugeService;
    @Autowired
    private EquipageMapper equipageMapper;
    @Autowired
    private MaterialsMapper materialsMapper;

    @Autowired
    ICsSystemMenuOrgInstitutionTemplateService templateService;

    @Autowired
    private ICsBusinessUserService csBusinessUserService;

    @Override
    public IDAASOrgEntity createCsSystemOrg(CsSystemOrgCreateBean bean) throws ParseException, JOSEException {
        if (ObjectUtils.isEmpty(bean)) {
            log.error("创建组织/部门的数据不允许为空!");
            throw new BizException("创建组织/部门的数据不允许为空!");
        }

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        HashMap<String, String> bodyParams = new HashMap<>();
        bodyParams.put("object_type", "DEPT");
        String url = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + bean.getAdminOrgID();
        String clientPostRes = HttpUtils.httpGet(url, bodyParams, headerParams);
        IDAASDeptResponse loginUserOrg = JSONObject.parseObject(clientPostRes, IDAASDeptResponse.class);
        if ("管理员".equals(loginUserOrg.getValues().getName())) {
            String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getValues().getParentId();
            String clientPostRes2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
            loginUserOrg = JSONObject.parseObject(clientPostRes2, IDAASDeptResponse.class);
        }

        /**
         * 解决管理员离职后重新启用,没有重新挂靠部门
         */
        if ("dpf-3f90f739227e498bb3505237e6c397bb".equals(loginUserOrg.getId()) && StringUtils.isNotEmpty(bean.getCreatedBy())) {
            CsSystemAdmin admin = service.getOne(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone, bean.getCreatedBy()).orderByDesc(CsSystemAdmin::getId).last("limit 1"));
            if (null != admin) {
                loginUserOrg.setId(admin.getOrgId());
            }
        }
        if ("成员单位".equals(bean.getMenuName())) {
            /**
             * 查询相关部门是否已经存在,如果存在则直接更新保存到本地库,如果不存在,先去 idaas 创建部门然后保存到本地;
             */
            String url0 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str0 = HttpUtils.httpGet(url0, bodyParams, headerParams);
            if (StringUtils.isNotEmpty(str0)) {
                /**
                 * 返回的响应字符串包含相关的行政区划代码,说明部门在IDAAS已经存在, 则直接入库记录
                 */
                IDAASDeptResponse interDeptResponse = getOrgInfoFromIDAASOrgList(str0, "成员单位");
                if (StringUtils.isNotEmpty(interDeptResponse.getId()) && !ObjectUtils.isEmpty(interDeptResponse.getValues())) {
                    /**
                     * 返回的子部门有成员单位就不用创建,直接获取相关成员单位机构信息,创建部门
                     */
                    String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + interDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                    if (!str2.contains(bean.getOrgName())) {
                        IDAASOrgEntity idaasOrg2 = createOrgToIDAAS(bean, "", interDeptResponse.getId());
                        preSetOffices(bean, idaasOrg2.getId());
                        return createOrgToIDAAS(bean, "管理员", idaasOrg2.getId());
                    } else {

                        IDAASDeptResponse idaasOrg3 = getOrgInfoFromIDAASOrgList(str2, bean.getOrgName());
                        preSetOffices(bean, idaasOrg3.getId());
                        String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + idaasOrg3.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                        String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);
                        if (!str3.contains("管理员")) {
                            return createOrgToIDAAS(bean, "管理员", idaasOrg3.getId());
                        } else {
                            return getOrgInfoFromIDAASOrgList(str3, "管理员").getValues();
                        }
                    }
                } else {
                    /**
                     * 否则:
                     * 1.先创建成员单位机构节点
                     * 2.创建相关组织节点
                     * 3.创建管理员节点
                     */
                    IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, "成员单位", loginUserOrg.getId());

                    IDAASOrgEntity idaasOrg2 = createOrgToIDAAS(bean, "", idaasOrg.getId());
                    preSetOffices(bean, idaasOrg2.getId());
                    return createOrgToIDAAS(bean, "管理员", idaasOrg2.getId());
                }
            } else {
                /**
                 *否则在在IDAAS创建部门
                 */
                try {
                    createOrgToIDAAS(bean, null, loginUserOrg.getId());
                } catch (ParseException e) {
                    e.printStackTrace();
                } catch (JOSEException e) {
                    e.printStackTrace();
                }
            }

        } else if ("内设机构".equals(bean.getMenuName())) {
            //获取子部门相关信息:/api/v1/departments/{department_id}/children
            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);

            if (str1.contains("内设机构")) {
                /**
                 * 返回的子部门有内设机构就不用创建,直接获取相关内设机构信息,创建部门
                 */
                IDAASDeptResponse interDeptResponse = getOrgInfoFromIDAASOrgList(str1, "内设机构");
                String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + interDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                //IDAASDeptResponse deptResponse = getOrgInfoFromIDAASOrgList(str2, bean.getOrgName());
                if (!str2.contains(bean.getOffice())) {
                    return createOrgToIDAAS(bean, "", interDeptResponse.getId());
                } else {
                    return getOrgInfoFromIDAASOrgList(str2, bean.getOffice()).getValues();
                }
            } else {
                /**
                 * 否则:
                 * 1.先创建内设机构节点
                 * 2.后创建内设机构
                 */
                IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, "内设机构", loginUserOrg.getId());
                return createOrgToIDAAS(bean, "", idaasOrg.getId());
            }

        } else if ("党委管理员".equals(bean.getMenuName())) {
            String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);
            if (str3.contains(bean.getOrgName())) {
                /**
                 * 返回的子部门有党委领导就不用创建
                 * 管理员节点在创建管理员考虑
                 */
                IDAASDeptResponse deptResponse = getOrgInfoFromIDAASOrgList(str3, bean.getOrgName());

                String url4 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + deptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str4 = HttpUtils.httpGet(url4, bodyParams, headerParams);
                if (!str4.contains("管理员")) {
                    return createOrgToIDAAS(bean, "管理员", deptResponse.getId());
                } else {
                    return getOrgInfoFromIDAASOrgList(str4, "管理员").getValues();
                }
            } else {
                /**
                 * ,否则创建党委领导,同时创建管理员部门节点
                 */
                IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, "", loginUserOrg.getId());
                return createOrgToIDAAS(bean, "管理员", idaasOrg.getId());
            }
        } else if ("政府管理员".equals(bean.getMenuName())) {
            String url4 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str4 = HttpUtils.httpGet(url4, bodyParams, headerParams);
            if (str4.contains(bean.getOrgName())) {
                /**
                 * 返回的子部门有政府领导相关的根节点就不用创建
                 * 再更具政府领导节点信息判断创建管理员
                 */
                IDAASDeptResponse deptResponse = getOrgInfoFromIDAASOrgList(str4, bean.getOrgName());

                String url5 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + deptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str5 = HttpUtils.httpGet(url5, bodyParams, headerParams);
                if (!str5.contains("管理员")) {
                    return createOrgToIDAAS(bean, "管理员", deptResponse.getId());
                } else {
                    return getOrgInfoFromIDAASOrgList(str5, "管理员").getValues();
                }
            } else {
                /**
                 * ,否则创政府委领导,同时创建管理员部门节点
                 */
                IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, "", loginUserOrg.getId());
                return createOrgToIDAAS(bean, "管理员", idaasOrg.getId());
            }
        } else if ("工委管理员".equals(bean.getMenuName())) {
            String url4 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str4 = HttpUtils.httpGet(url4, bodyParams, headerParams);
            if (str4.contains("工委领导")) {
                /**
                 * 返回的子部门有工委领导就不用创建
                 * 再根据工委领导节点信息判断创建管理员
                 */
                IDAASDeptResponse deptResponse = getOrgInfoFromIDAASOrgList(str4, "工委领导");

                String url5 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + deptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str5 = HttpUtils.httpGet(url5, bodyParams, headerParams);
                if (!str5.contains("管理员")) {
                    return createOrgToIDAAS(bean, "管理员", deptResponse.getId());
                } else {
                    return getOrgInfoFromIDAASOrgList(str5, "管理员").getValues();
                }
            } else {
                /**
                 * ,否则创政府委领导,同时创建管理员部门节点
                 */
                IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, "工委领导", loginUserOrg.getId());
                return createOrgToIDAAS(bean, "管理员", idaasOrg.getId());
            }
        } else if ("救援队伍".equals(bean.getMenuName())) {
            if (!"2".equals(bean.getPageType())) {
                //获取子部门相关信息:/api/v1/departments/{department_id}/children
                String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);

                IDAASDeptResponse teamDeptResponse = getOrgInfoFromIDAASOrgList(str1, "救援队伍");
                if (StringUtils.isNotEmpty(teamDeptResponse.getId())) {
                    /**
                     * 返回的子部门有救援队伍节点就不用创建,直接获取相关救援队伍节点信息,创建救援队伍节点
                     */
                    String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + teamDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                    if (!str2.contains("管理员")) {
                        return createOrgToIDAAS(bean, "管理员", teamDeptResponse.getId());
                    } else {
                        return getOrgInfoFromIDAASOrgList(str2, "管理员").getValues();
                    }
                } else {
                    IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, "救援队伍", loginUserOrg.getId());
                    return createOrgToIDAAS(bean, "管理员", idaasOrg.getId());
                }
            } else {
                String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
                IDAASDeptResponse teamDeptResponse = getOrgInfoFromIDAASOrgList(str1, bean.getOrgName());
                if (null == teamDeptResponse || StringUtils.isEmpty(teamDeptResponse.getId())) {
                    return createOrgToIDAAS(bean, "", loginUserOrg.getId());
                } else {
                    return teamDeptResponse.getValues();
                }
            }

        } else if ("避难场所".equals(bean.getMenuName())) {
            if (!"2".equals(bean.getPageType())) {
                //获取子部门相关信息
                String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
                IDAASDeptResponse teamDeptResponse = getOrgInfoFromIDAASOrgList(str1, "避难场所");
                if (StringUtils.isNotEmpty(teamDeptResponse.getId())) {
                    /**
                     * 返回的子部门有避难场所节点就不用创建,直接获取相关避难场所节点信息,创建避难场所节点
                     */
                    String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + teamDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                    if (!str2.contains("管理员")) {
                        return createOrgToIDAAS(bean, "管理员", teamDeptResponse.getId());
                    } else {

                        return getOrgInfoFromIDAASOrgList(str2, "管理员").getValues();
                    }
                } else {
                    IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, "避难场所", loginUserOrg.getId());
                    return createOrgToIDAAS(bean, "管理员", idaasOrg.getId());
                }
            } else {
                String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
                IDAASDeptResponse teamDeptResponse = getOrgInfoFromIDAASOrgList(str1, bean.getOrgName());
                if (null == teamDeptResponse || StringUtils.isEmpty(teamDeptResponse.getId())) {
                    return createOrgToIDAAS(bean, "", loginUserOrg.getId());
                } else {
                    return teamDeptResponse.getValues();
                }
            }
        } else if ("应急物资".equals(bean.getMenuName())) {
            if (!"2".equals(bean.getPageType())) {
                //获取子部门相关信息
                String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
                IDAASDeptResponse teamDeptResponse = getOrgInfoFromIDAASOrgList(str1, "应急物资");
                if (StringUtils.isNotEmpty(teamDeptResponse.getId())) {
                    /**
                     * 返回的子部门有应急物资节点就不用创建,直接获取相关应急物资节点信息,否则创建应急物资节点
                     */
                    String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + teamDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                    if (!str2.contains("管理员")) {
                        return createOrgToIDAAS(bean, "管理员", teamDeptResponse.getId());
                    } else {
                        return getOrgInfoFromIDAASOrgList(str2, "管理员").getValues();
                    }
                } else {
                    IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, "应急物资", loginUserOrg.getId());
                    return createOrgToIDAAS(bean, "管理员", idaasOrg.getId());
                }

            } else {
                String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
                IDAASDeptResponse teamDeptResponse = getOrgInfoFromIDAASOrgList(str1, bean.getOrgName());
                if (null == teamDeptResponse || StringUtils.isEmpty(teamDeptResponse.getId())) {
                    return createOrgToIDAAS(bean, "", loginUserOrg.getId());
                } else {
                    return teamDeptResponse.getValues();
                }

            }
        } else if (("专家库").equals(bean.getMenuName())) {
            //获取子部门相关信息:/api/v1/departments/{department_id}/children
            //adminService.getOne(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone,loginUserOrg.))
            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
            IDAASDeptResponse teamDeptResponse = getOrgInfoFromIDAASOrgList(str1, "专家");
            if (StringUtils.isNotEmpty(teamDeptResponse.getId())) {
                /**
                 * 返回的子部门有专家库节点就不用创建,直接获取相关专家库节点信息,否则创建专家库资节点
                 */
                String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + teamDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                if (!str2.contains("管理员")) {
                    return createOrgToIDAAS(bean, "管理员", teamDeptResponse.getId());
                } else {
                    return getOrgInfoFromIDAASOrgList(str2, "管理员").getValues();
                }
            } else {
                IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, "专家", loginUserOrg.getId());
                return createOrgToIDAAS(bean, "管理员", idaasOrg.getId());
            }
        } else if (("防护目标").equals(bean.getMenuName())) {
            if (!"2".equals(bean.getPageType())) {
                //获取子部门相关信息:/api/v1/departments/{department_id}/children
                String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
                IDAASDeptResponse teamDeptResponse = getOrgInfoFromIDAASOrgList(str1, "防护目标");
                if (StringUtils.isNotEmpty(teamDeptResponse.getId())) {
                    /**
                     * 返回的子部门有防护目标节点就不用创建,直接获取相关防护目标节点信息,否则创建防护目标资节点
                     */
                    String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + teamDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                    if (!str2.contains("管理员")) {
                        return createOrgToIDAAS(bean, "管理员", teamDeptResponse.getId());
                    } else {
                        return getOrgInfoFromIDAASOrgList(str2, "管理员").getValues();
                    }
                } else {
                    IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, "防护目标", loginUserOrg.getId());
                    return createOrgToIDAAS(bean, "管理员", idaasOrg.getId());
                }
            } else {
                String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
                IDAASDeptResponse teamDeptResponse = getOrgInfoFromIDAASOrgList(str1, bean.getOrgName());
                if (null == teamDeptResponse || StringUtils.isEmpty(teamDeptResponse.getId())) {
                    return createOrgToIDAAS(bean, "", loginUserOrg.getId());
                } else {
                    return teamDeptResponse.getValues();
                }

            }
        } else if (("嘎查、村、屯").equals(bean.getMenuName())) {
            //获取子部门相关信息:/api/v1/departments/{department_id}/children
            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
            if (str1.contains("嘎查、村、屯")) {
                IDAASDeptResponse teamDeptResponse = getOrgInfoFromIDAASOrgList(str1, "嘎查、村、屯");
                return createOrgToIDAAS(bean, "", teamDeptResponse.getId());
            } else {
                IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, "嘎查、村、屯", loginUserOrg.getId());
                return createOrgToIDAAS(bean, "", idaasOrg.getId());
            }
        } else if (("盟市指挥体系").equals(bean.getMenuName()) || ("旗县指挥体系").equals(bean.getMenuName())) {
            //获取子部门相关信息:/api/v1/departments/{department_id}/children

            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
            IDAASDeptResponse teamDeptResponse = getOrgInfoFromIDAASOrgList(str1, bean.getMenuName());

            if (StringUtils.isNotEmpty(teamDeptResponse.getId())) {
                String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + teamDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);

                if (!str2.contains(bean.getOrgName())) {
                    IDAASOrgEntity detpToDAAS = createOrgToIDAAS(bean, "", teamDeptResponse.getId());
                    return createOrgToIDAAS(bean, "管理员", detpToDAAS.getId());
                } else {
                    IDAASDeptResponse teamDeptResponse2 = getOrgInfoFromIDAASOrgList(str2, bean.getOrgName());
                    String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + teamDeptResponse2.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);

                    if (!str3.contains("管理员")) {
                        return createOrgToIDAAS(bean, "管理员", teamDeptResponse2.getId());
                    } else {
                        return getOrgInfoFromIDAASOrgList(str3, "管理员").getValues();
                    }
                }
            } else {
                IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, bean.getMenuName(), loginUserOrg.getValues().getId());
                IDAASOrgEntity detpToDAAS = createOrgToIDAAS(bean, "", idaasOrg.getId());
                return createOrgToIDAAS(bean, "管理员", detpToDAAS.getId());
            }
        } else if (("乡镇指挥体系").equals(bean.getMenuName())) {
            //获取子部门相关信息:/api/v1/departments/{department_id}/children

            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
            IDAASDeptResponse teamDeptResponse = getOrgInfoFromIDAASOrgList(str1, "乡镇指挥体系");

            if (StringUtils.isNotEmpty(teamDeptResponse.getId())) {
                String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + teamDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                IDAASDeptResponse teamDeptResponse2 = getOrgInfoFromIDAASOrgList(str2, bean.getOrgName());
                if (StringUtils.isNotEmpty(teamDeptResponse2.getId())) {
                    /**
                     * 返回的子部门有乡镇/街道就不用创建,直接获取相关乡镇/街道乡镇/街道节点信息,否则创建乡镇/街道节点
                     */
                    String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + teamDeptResponse2.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);
                    if (!str3.contains("指挥体系成员")) {
                        return createOrgToIDAAS(bean, "指挥体系成员", teamDeptResponse2.getId());
                    } else {
                        return getOrgInfoFromIDAASOrgList(str3, "指挥体系成员").getValues();
                    }
                } else {
                    IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, "", loginUserOrg.getId());
                    return createOrgToIDAAS(bean, "指挥体系成员", idaasOrg.getId());
                }
            } else {
                IDAASOrgEntity idaasOrg = createOrgToIDAAS(bean, bean.getMenuName(), loginUserOrg.getId());
                IDAASOrgEntity detpToDAAS = createOrgToIDAAS(bean, "", idaasOrg.getId());
                return createOrgToIDAAS(bean, "指挥体系成员", detpToDAAS.getId());
            }

        } else if ("事业单位".equals(bean.getMenuName())) {
            //获取子部门相关信息:/api/v1/departments/{department_id}/children
            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + loginUserOrg.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
            IDAASDeptResponse interDeptResponse = getOrgInfoFromIDAASOrgList(str1, "事业单位");
            /**
             * 返回的响应字符串包含相关的行政区划代码,说明部门在IDAAS已经存在, 则直接入库记录
             */
            if (StringUtils.isNotEmpty(interDeptResponse.getId()) && !ObjectUtils.isEmpty(interDeptResponse.getValues())) {
                /**
                 * 返回的子部门有成员单位就不用创建,直接获取相关成员单位机构信息,创建部门
                 */
                String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + interDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                IDAASDeptResponse deptResponse = getOrgInfoFromIDAASOrgList(str2, bean.getOrgName());
                if (StringUtils.isNotEmpty(deptResponse.getId())) {
                    String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + deptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);
                    if (!str3.contains("管理员")) {
                        return createOrgToIDAAS(bean, "管理员", deptResponse.getId());
                    } else {
                        return getOrgInfoFromIDAASOrgList(str3, "管理员").getValues();
                    }
                } else {
                    IDAASOrgEntity idaasOrg2 = createOrgToIDAAS(bean, bean.getOrgName(), interDeptResponse.getId());
                    return createOrgToIDAAS(bean, "管理员", idaasOrg2.getId());
                }
            } else {
                /**
                 * 否则:
                 * 1.先创建成员单位机构节点
                 * 2.后创建相关组织
                 * 3.创建相关组织的管理员节点
                 */
                IDAASOrgEntity idaasOrg1 = createOrgToIDAAS(bean, "事业单位", loginUserOrg.getId());
                IDAASOrgEntity idaasOrg2 = createOrgToIDAAS(bean, bean.getOrgName(), idaasOrg1.getId());
                return createOrgToIDAAS(bean, "管理员", idaasOrg2.getId());
            }
        }
        //入库操作
        return null;
    }

    @Override
    public IDAASOrgEntity updateCsSystemOrg(CsSystemOrgCreateBean bean) throws ParseException, JOSEException {
        return null;
    }


    IDAASOrgEntity createOrgToIDAAS(CsSystemOrgCreateBean dept, String orgName, String parentId) throws ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "Bearer " + NMGYJTIDAASTokenUtils.getToken());

        IDAASOrgEntity po = new IDAASOrgEntity();
        String areaCode = dept.getAreaCode().substring(0, 9);
        po.setOrgType("ob-1def915f1cb04dc190d48ea9cbf0f52c");
        po.setStatus("ENABLED");
        po.setRegionCode(areaCode);
        po.setParentId(parentId);
        po.setUdOrder(dept.getUdOrder());

        String[] areaMenus = {"1000000003", "1000000004", "1000000005"};
        List<String> areaMenusList = Arrays.asList(areaMenus);
        IdaasArea area = null;
        if (!areaMenusList.contains(dept.getMenuID())) {
            area = idaasAreaService.getOne(new LambdaQueryWrapper<IdaasArea>().eq(IdaasArea::getCode, areaCode));
        } else {
            area = idaasAreaService.getOne(new LambdaQueryWrapper<IdaasArea>().eq(IdaasArea::getCode, dept.getAreaCode()));
        }
        if (null != area) {
            po.setArea(area.getId());
            po.setRegionCode(area.getCode().substring(0, 9));
        } else {
            /**
             *  todo  idaas的 Area 不存在,创建area,并同步到数据库;
             */
            IDAASAreaEntity idaasArea = new IDAASAreaEntity();
            IDAASAreaValuesEntity valuesEntity = new IDAASAreaValuesEntity();
            valuesEntity.setName(dept.getOrgName());
            if ("1000000003".equals(dept.getMenuID()) || "1000000004".equals(dept.getMenuID()) || "1000000005".equals(dept.getMenuID())) {
                if ("1000000003".equals(dept.getMenuID())) {
                    Area city = areaService.getOne(new LambdaQueryWrapper<Area>().eq(Area::getRemark, "City").eq(Area::getParId, "150000000000").orderByDesc(Area::getId).last("limit 1"));
                    IdaasArea idaasArea2 = idaasAreaService.getOne(new LambdaQueryWrapper<IdaasArea>().eq(IdaasArea::getCode, city.getId().substring(0, 9)));
                    if (null != idaasArea2)
                        valuesEntity.set_preId(idaasArea2.getId());
                    if (null != city) {
                        String code = city.getId().substring(0, 4);
                        code = Integer.valueOf(code) + 1 + "";
                        valuesEntity.setCode(StringUtils.rightPad(code, 9, "0"));
                    }
                    valuesEntity.setParentId("ob-3217938a528f4e5a9d5d3b538fecd786");
                    valuesEntity.setHasChild(true);
                    idaasArea.setValues(valuesEntity);

                } else if ("1000000004".equals(dept.getMenuID()) || "1000000005".equals(dept.getMenuID())) {
                    String remark = "County";
                    if ("1000000005".equals(dept.getMenuID()))
                        remark = "Town";
                    Area city = areaService.getOne(new LambdaQueryWrapper<Area>().eq(Area::getRemark, remark).eq(Area::getParId, StringUtils.rightPad(dept.getAreaCode(), 12, "0")).orderByDesc(Area::getId).last("limit 1"));
                    if (null != city) {
                        String code = null;
                        if (remark == "County") {
                            code = city.getId().substring(0, 6);
                        } else {
                            code = city.getId().substring(0, 9);
                        }

                        code = Integer.valueOf(code) + 1 + "";
                        valuesEntity.setCode(StringUtils.rightPad(code, 9, "0"));

                        IdaasArea idaasArea2 = idaasAreaService.getOne(new LambdaQueryWrapper<IdaasArea>().eq(IdaasArea::getCode, city.getId().substring(0, 9)));
                        if (null != idaasArea2) {
                            valuesEntity.set_preId(idaasArea2.getId());
                            valuesEntity.setParentId(idaasArea2.getParId());
                        }
                    }
                    idaasArea.setValues(valuesEntity);
                }
                IdaasArea idaasAreaCheck = idaasAreaService.getOne(new LambdaQueryWrapper<IdaasArea>().eq(IdaasArea::getCode, valuesEntity.getCode()));
                if (null == idaasAreaCheck) {
                    String areaPostRes = HttpUtils.sendHttpPost("http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects", (JSONObject) JSON.toJSON(idaasArea), headerParams);
                    if (StringUtils.isNotEmpty(areaPostRes)) {
                        IDAASCreateAreaResponse areaResponse = JSONObject.parseObject(areaPostRes, IDAASCreateAreaResponse.class);
                        if (null != areaResponse && StringUtils.isNotEmpty(areaResponse.getId())) {
                            IdaasArea idaasArea3 = new IdaasArea();
                            idaasArea3.setId(areaResponse.getId());
                            idaasArea3.setCode(areaResponse.getValues().getCode());
                            idaasArea3.setName(areaResponse.getValues().getName());
                            idaasArea3.setParId(areaResponse.getValues().getParentId());
                            idaasArea3.setStatus("ENABLED");
                            po.setArea(areaResponse.getId());
                            po.setRegionCode(areaResponse.getValues().getCode());
                            idaasAreaService.save(idaasArea3);

                       /* Area area2 = new Area();
                        area2.setId(StringUtils.rightPad(areaResponse.getValues().getCode(), 12, "0"));
                        area2.setName(dept.getOrgName());
                        area2.setParId(StringUtils.rightPad(dept.getAreaCode(), 12, "0"));

                        if ("1000000003".equals(dept.getMenuID()))
                            area2.setRemark("City");
                        if ("1000000004".equals(dept.getMenuID()))
                            area2.setRemark("County");
                        if ("1000000005".equals(dept.getMenuID()))
                            area2.setRemark("Town");
                        areaService.save(area2);*/

                        }
                    }
                } else {
                    po.setArea(idaasAreaCheck.getId());
                    po.setRegionCode(idaasAreaCheck.getCode());
                }
            }

            /*Area area1 = areaService.getById(StringUtils.rightPad(areaCode, 12, "0"));
            IdaasArea area2 = idaasAreaService.getOne(new LambdaQueryWrapper<IdaasArea>().eq(IdaasArea::getCode, StringUtils.substring(area1.getParId(), 0, 9)));
            if (null != area2) {
                po.setArea(area2.getId());
            } else {
                Area area3 = areaService.getById(area1.getId());
                IdaasArea area4 = idaasAreaService.getOne(new LambdaQueryWrapper<IdaasArea>().eq(IdaasArea::getCode, StringUtils.substring(area3.getParId(), 0, 9)));
                if (null != area4)
                    po.setArea(area4.getId());
            }*/
        }

        if (StringUtils.isNotEmpty(orgName)) {
            po.setName(orgName);
        } else {
            if (!areaMenusList.contains(dept.getMenuID()) && !"1000000006".equals(dept.getMenuID()) && StringUtils.isNotEmpty(dept.getOffice())) {
                po.setName(dept.getOffice());
            } else {
                po.setName(dept.getOrgName());
            }
        }
        if (StringUtils.isNotEmpty(dept.getSourceType())) {
            CsSystemSourceType sourceType = sourceService.getById(dept.getSourceType());
            if (null != sourceType) {
                po.setSourceType(sourceType.getName());
            } else {
                po.setSourceType(dept.getSourceType());
            }
        }
        //创建部门的时候设置默认排序值,保证排序顺序
        if (null == dept.getUdOrder()) {
            if ("管理员".equals(po.getName())) {
                po.setUdOrder(999);
            } else if ("单位领导".equals(po.getName())) {
                po.setUdOrder(1);
            } else if ("内设机构".equals(po.getName())) {
                po.setUdOrder(3);
            } else if ("事业单位".equals(po.getName())) {
                po.setUdOrder(5);
            } else if ("救援队伍".equals(po.getName())) {
                po.setUdOrder(7);
            } else if ("专家".equals(po.getName())) {
                po.setUdOrder(9);
            } else if ("防护目标".equals(po.getName())) {
                po.setUdOrder(11);
            } else if ("避难场所".equals(po.getName())) {
                po.setUdOrder(13);
            } else {
                po.setUdOrder(20);
            }
        }

        if ("1000000006".equals(dept.getMenuID()) || "1000000007".equals(dept.getMenuID())) {
            po.setMaxUserNumber(null == dept.getMaxUserNumber() ? 20 : dept.getMaxUserNumber());
        }

        Map map = new HashMap<>();
        map.put("values", po);
        String clientPostRes = HttpUtils.sendHttpPost("http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/", (JSONObject) JSON.toJSON(map), headerParams);

        IDAASDeptResponse org = JSONObject.parseObject(clientPostRes, IDAASDeptResponse.class);

        po.setId(org.getId());
        //  po.setParentId(org.getValues().getParentId());
        String[] menus = {"1000000010", "1000000011", "1000000012", "1000000014"};
        String[] orgNames = {"救援队伍", "应急物资", "防护目标", "避难场所"};
        List<String> menuList = Arrays.asList(menus);
        List<String> orgLst = Arrays.asList(orgNames);

        if (null != dept.getMenuID() && menuList.contains(dept.getMenuID())) {
            Map<String, String> bodyParam = new HashMap();
            bodyParam.put("object_type", "DEPT");
            String parentOrgRes = HttpUtils.httpGet("http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + org.getValues().getParentId(), bodyParam, headerParams);

            IDAASDeptResponse patentOrg = JSONObject.parseObject(parentOrgRes, IDAASDeptResponse.class);
            if (orgLst.contains(patentOrg.getValues().getName())) {

                CsSystemSourceExt sourceExt = new CsSystemSourceExt();
                sourceExt.setId(SnowflakeIdWorker.getUUID());
                sourceExt.setMenuId(dept.getMenuID());
                sourceExt.setRemark(dept.getDesc());
                sourceExt.setSourceType(dept.getSourceType());
                sourceExt.setOrgId(org.getId());
                sourceExt.setSourceLevel(JSONObject.toJSONString(dept.getSourceLevel()));

                Map<String, String> bodyParam2 = new HashMap();
                bodyParam2.put("object_type", "DEPT");
                String parentOrgRes2 = HttpUtils.httpGet("http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + patentOrg.getValues().getParentId(), bodyParam2, headerParams);
                IDAASDeptResponse patentOrg2 = JSONObject.parseObject(parentOrgRes2, IDAASDeptResponse.class);
                if (null != patentOrg2 && null != patentOrg2.getValues()) {
                    sourceExt.setSuperiorOrgId(patentOrg2.getId());
                    sourceExt.setSuperiorOrgName(patentOrg2.getValues().getName());
                }

                if ("1000000010".equals(dept.getMenuID())) {
                    //20240307李处要求主要救援去掉
//                    if (StringUtils.isNotEmpty(dept.getMajorDuties()))
//                        sourceExt.setMajorDuties(dept.getMajorDuties());
                    if (StringUtils.isNotEmpty(dept.getSecondaryDuties()))
                        sourceExt.setSecondaryDuties(dept.getSecondaryDuties());
                }

                CsSystemSourceExt sourceExt1 = csSystemSourceExtService.getOne(new LambdaQueryWrapper<CsSystemSourceExt>().eq(CsSystemSourceExt::getOrgId, org.getId()).eq(CsSystemSourceExt::getMenuId, dept.getMenuID()));
                if (null != sourceExt1) {
                    sourceExt.setId(sourceExt1.getId());
                }

                csSystemSourceExtService.saveOrUpdate(sourceExt);
                //保存基础资源
                idaasService.saveBaseSource(sourceExt, dept);
            }
        }
        return po;
    }


    IDAASDeptResponse getOrgInfoFromIDAASOrgList(String clientPostRes, String orgName) {

        IDAASDeptResponse deptResponse = new IDAASDeptResponse();
        List<IDAASDeptResponse> listResponse = JSONArray.parseArray(clientPostRes, IDAASDeptResponse.class);
        if (!CollectionUtils.isEmpty(listResponse)) {
            for (IDAASDeptResponse dept : listResponse) {
                if (orgName.equals(dept.getValues().getName())) {
                    BeanUtils.copyProperties(dept, deptResponse);
                    if (StringUtils.isEmpty(deptResponse.getValues().getId()) || null == deptResponse.getValues().getId()) {
                        IDAASOrgEntity values = deptResponse.getValues();
                        values.setId(dept.getId());
                        values.setAncestor(dept.getValues().getAncestor());
                        deptResponse.setValues(values);
                    }
                    break;
                }
            }
        }
        return deptResponse;
    }


    @Override
    public List<CsSystemAdminAndOrgInfo> selectOrgList(CsSystemOrgSelectBean bean) throws Exception {
       /* UserInfo loginAdminInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(bean.getCreatedBy());

        if (ObjectUtils.isEmpty(loginAdminInfo)) {
            log.error("管理员账号非法,查询失败,查询信息如下:{}", bean);
            throw new BizException("查询统一认证用户失败,请联系系统管理员!");
        }*/
        CsSystemAdmin admin = adminService.getOne(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone, bean.getCreatedBy()).eq(CsSystemAdmin::getOrgId, bean.getOrgId()).orderByDesc(CsSystemAdmin::getUpdatedTime).last("limit 1"));

        if (ObjectUtils.isEmpty(admin)) {
            log.error("管理员账号非法,查询失败,查询信息如下:{}", bean);
            throw new BizException("管理员账号权限为空,请联系系统管理员!");
        }
        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        HashMap bodyParams = new HashMap<>();
        bodyParams.put("object_type", "DEPT");
        CsSystemAdminMenuRel menuRel = menuRelService.getById(bean.getMenuID());
        if ("1000000007".equals(menuRel.getId())) {
            menuRel.setName("内设机构");
        }

        List<CsSystemAdminAndOrgInfo> adminsAndDeptInfos = new ArrayList<>();
        List<IDAASDeptResponse> listResponse = new ArrayList<>();

        if ("1000000008".equals(menuRel.getId())) {
            String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + admin.getOrgId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);
            IDAASDeptResponse idaasDeptResponse = getOrgInfoFromIDAASOrgList(str3, "事业单位");

            String url4 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + idaasDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str4 = HttpUtils.httpGet(url4, bodyParams, headerParams);
            List<IDAASDeptResponse> depts = JSONArray.parseArray(str4, IDAASDeptResponse.class);
            if (!CollectionUtils.isEmpty(depts))
                if (!CollectionUtils.isEmpty(depts)) {
                    listResponse = depts;
                }
        } else if ("1000000007".equals(menuRel.getId()) || "1000000003".equals(menuRel.getId()) || "1000000004".equals(menuRel.getId()) || "1000000005".equals(menuRel.getId()) || "1000000006".equals(menuRel.getId()) || "1000000016".equals(menuRel.getId())) {

            Map<String, String> bodyParam = new HashMap();
            bodyParam.put("object_type", "DEPT");

            String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + admin.getOrgId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);
            IDAASDeptResponse interDeptResponse = deptService.getOrgInfoFromIDAASOrgList(str3, menuRel.getName());

            String url4 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + interDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_regionCode&order_by=_udOrder&order_by=_createdOn";
            String str4 = HttpUtils.httpGet(url4, bodyParams, headerParams);
            List<IDAASDeptResponse> responseList = JSONArray.parseArray(str4, IDAASDeptResponse.class);
            listResponse.addAll(responseList);

        } else if ("1000000010".equals(menuRel.getId()) || "1000000011".equals(menuRel.getId()) || "1000000012".equals(menuRel.getId()) || "1000000013".equals(menuRel.getId()) || "1000000014".equals(menuRel.getId())) {

            String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + admin.getOrgId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);

            List<IDAASDeptResponse> resourceDepts = JSONArray.parseArray(str3, IDAASDeptResponse.class);

            if (!CollectionUtils.isEmpty(resourceDepts)) {
                listResponse = resourceDepts;
            }
        } else {

            String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + admin.getOrgId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
            IDAASDeptResponse deptResponse = getOrgInfoFromIDAASOrgList(str2, menuRel.getName());
            List<IDAASDeptResponse> resourceDepts = JSONArray.parseArray(str2, IDAASDeptResponse.class);
            if (!CollectionUtils.isEmpty(resourceDepts)) {
                listResponse = resourceDepts;
            }
        }

        if (!CollectionUtils.isEmpty(listResponse)) {

            HashMap<String, String> headerParams2 = new HashMap<>();
            headerParams2.put("Content-Type", "application/json");
            try {
                headerParams2.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (JOSEException e) {
                e.printStackTrace();
            }
            for (IDAASDeptResponse dept : listResponse) {
                if (!"管理员".equals(dept.getValues().getName()) && "ENABLED".equals(dept.getValues().getStatus())) {

                    CsSystemAdminAndOrgInfo csSystemAdmin = new CsSystemAdminAndOrgInfo();
                   /* if ("1000000006".equals(bean.getMenuID())) {
                        HashMap bodyParams3 = new HashMap<>();
                        Map<Object, Object> objectMap = new HashMap<>();
                        objectMap.put("status", new ArrayList<>());
                        objectMap.put("identityClassification", "defaultIdentityClassification");
                        bodyParams3.put("objectType", "USER");
                        List<String> idList = new ArrayList<>();
                        idList.add(dept.getId());
                        objectMap.put("deptId", idList);
                        bodyParams3.put("values", objectMap);
                        String userNumberUrl = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/top_user/" + dept.getId() + "/query?page_index=0&page_size=10&order_by=_udOrder&order_by=_displayName&need_child_depts=true";
                        String str2 = HttpUtils.sendHttpPost(userNumberUrl, (JSONObject) JSON.toJSON(bodyParams3), headerParams2);

                        IDAASUserResponse object = JSONObject.parseObject(str2, IDAASUserResponse.class);
                        csSystemAdmin.setUserNumber(object.getTotal());
                    }*/
                    List<CsSystemAdmin> admins = service.list(
                            CsSystemAdmin.gw().eq(CsSystemAdmin::getOrgId, dept.getId()));
                    if (CollectionUtils.isEmpty(admins)) {
                        csSystemAdmin.setOrgName(dept.getValues().getName());
                        csSystemAdmin.setOrgId(dept.getId());
                        csSystemAdmin.setSuperiorOrg(admin.getOrgId());
                        csSystemAdmin.setUdOrder(Integer.valueOf(dept.getValues().getUdOrder()));
                        csSystemAdmin.setName("");
                        csSystemAdmin.setJob("");
                        csSystemAdmin.setPhone("");
                        csSystemAdmin.setOffice("");
                        csSystemAdmin.setId("");
                        csSystemAdmin.setMaxUserNumber(dept.getValues().getMaxUserNumber());
                        csSystemAdmin.setUserNumber(dept.getValues().getUserNumber());

                        if ("1000000007".equals(bean.getMenuID())) {
                            csSystemAdmin.setOffice(dept.getValues().getName());
                        }
                    } else {
                        BeanUtils.copyProperties(admins.get(admins.size() - 1), csSystemAdmin);
                        csSystemAdmin.setOrgName(dept.getValues().getName());
                        csSystemAdmin.setMaxUserNumber(dept.getValues().getMaxUserNumber());
                        csSystemAdmin.setUserNumber(dept.getValues().getUserNumber());

                        if ("1000000007".equals(bean.getMenuID())) {
                            csSystemAdmin.setOffice(dept.getValues().getName());
                        }

                        /**
                         //获取机构的预设成员单位数据
                         String permissionStr = csSystemAdmin.getMenuPermission().replace("::", "");
                         permissionStr = permissionStr.replace(":", ",");
                         if (StringUtils.isNotEmpty(permissionStr)) {
                         List<String> permissionList = Arrays.asList(permissionStr.split(","));
                         List<CsSystemOrgPreSetBean> preSetOrgInfos = new ArrayList<>();
                         if (!CollectionUtils.isEmpty(permissionList)) {
                         for (String p : permissionList) {
                         CsSystemOrgPreSetBean preSetBean = new CsSystemOrgPreSetBean();

                         if ("1000000007".equals(p)) {

                         List<IDAASDeptResponse> responseList = new ArrayList<>();
                         if (!"1000000007".equals(bean.getMenuID())) {
                         String preSetOfficeUrl = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + dept.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                         String preSetOfficeStr = HttpUtils.httpGet(preSetOfficeUrl, bodyParams, headerParams);
                         IDAASDeptResponse interDeptResponse = deptService.getOrgInfoFromIDAASOrgList(preSetOfficeStr, "内设机构");

                         String preSetOfficeDetailUrl = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + interDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_regionCode&order_by=_udOrder&order_by=_createdOn";
                         String preSetOfficeStrDetail = HttpUtils.httpGet(preSetOfficeDetailUrl, bodyParams, headerParams);
                         responseList = JSONArray.parseArray(preSetOfficeStrDetail, IDAASDeptResponse.class);
                         } else {

                         String preSetOfficeUrl = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + dept.getId();
                         String preSetOfficeStr = HttpUtils.httpGet(preSetOfficeUrl, bodyParams, headerParams);
                         IDAASDeptResponse idaasDeptResponse = JSONObject.parseObject(preSetOfficeStr, IDAASDeptResponse.class);
                         responseList.add(idaasDeptResponse);
                         }

                         List<CsSystemOrgItemPreSetBean> offices = new ArrayList<>();
                         if (!CollectionUtils.isEmpty(responseList)) {
                         Map bodyParam = new HashMap();
                         HashMap bodyParams2 = new HashMap<>();
                         bodyParam.put("status", new ArrayList<>());
                         bodyParam.put("identityClassification", "defaultIdentityClassification");
                         bodyParams2.put("objectType", "USER");

                         responseList.forEach(o -> {
                         if ("ENABLED".equals(o.getValues().getStatus())) {

                         CsSystemOrgItemPreSetBean office = new CsSystemOrgItemPreSetBean();
                         office.setMaxUserNumber(null == o.getValues().getMaxUserNumber() ? 20 : o.getValues().getMaxUserNumber());
                         office.setId(o.getId());
                         office.setName(o.getValues().getName());

                         List<String> orgId = new ArrayList<>();
                         orgId.add(o.getId());
                         bodyParam.put("deptId", orgId);
                         bodyParams2.put("values", bodyParam);


                         String url2 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/top_user/" + o.getId() + "/query?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName&need_child_depts=true";
                         String str2 = HttpUtils.sendHttpPost(url2, (JSONObject) JSON.toJSON(bodyParams2), headerParams2);

                         IDAASUserResponse object = JSONObject.parseObject(str2, IDAASUserResponse.class);
                         office.setUserNumber(object.getTotal());
                         // csSystemAdmin.setUserNumber(object.getTotal());
                         if (object.getTotal() > 0) {
                         office.setDeleteStatus(false);
                         }
                         offices.add(office);
                         }
                         }
                         );
                         }
                         preSetBean.setOrgChildren(offices);
                         }

                         if ("1000000012".equals(p) || "1000000014".equals(p)) {
                         List<Object> data = new ArrayList<>();
                         List<List<String>> data2 = new ArrayList<>();
                         List<String> data3 = new ArrayList<>();
                         CsSystemSourcePreSetInfo one = preSetInfoService.getOne(new LambdaQueryWrapper<CsSystemSourcePreSetInfo>().eq(CsSystemSourcePreSetInfo::getOrgId, csSystemAdmin.getOrgId()).eq(CsSystemSourcePreSetInfo::getSourceId, p).orderByDesc(CsSystemSourcePreSetInfo::getId).last("limit 1"));
                         if (null != one && StringUtils.isNotEmpty(one.getPreSetTypes()))
                         data = JSONObject.parseObject(one.getPreSetTypes(), List.class);
                         if (!CollectionUtils.isEmpty(data)) {
                         for (Object str : data) {
                         List<String> list = Arrays.asList(str.toString().replace("\"[", "").replace("]\"", "").replace("[", "").replace("]", "").replace("\"", "").split(","));
                         data2.add(list);
                         if (null != list && !CollectionUtils.isEmpty(list)) {
                         CsSystemSourceType sourceType = iCsSystemSourceTypeService.getById(list.get(list.size() - 1));
                         if (null != sourceType) {
                         data3.add(sourceType.getName());
                         }
                         }
                         }
                         }
                         preSetBean.setChildren(data2);
                         preSetBean.setChildrenText(data3);
                         }
                         preSetBean.setId(p);
                         preSetOrgInfos.add(preSetBean);

                         }
                         csSystemAdmin.setPreSetOrgInfos(preSetOrgInfos);
                         }

                         }
                         **/
                    }
                    if (null != dept.getValues() && StringUtils.isNotEmpty(dept.getValues().getRegionCode())) {
                        Area area = areaService.getById(StringUtils.rightPad(dept.getValues().getRegionCode(), 12, "0"));
                        if (null != area) {
                            csSystemAdmin.setAreaCode(area.getId());
                            csSystemAdmin.setAreaName(area.getName());
                        }
                    }

                    String[] menus = {"1000000010", "1000000011", "1000000012", "1000000014"};
                    List<String> menuList = Arrays.asList(menus);
                    CsSystemSourceLevelBean sourceExt = new CsSystemSourceLevelBean();
                    sourceExt.setCountry("");
                    if (null != bean.getMenuID() && menuList.contains(bean.getMenuID())) {
                        List<CsSystemSourceExt> sourceExts =
                                csSystemSourceExtService.list(new LambdaQueryWrapper<CsSystemSourceExt>()
                                        .eq(CsSystemSourceExt::getMenuId, bean.getMenuID())
                                        .eq(CsSystemSourceExt::getOrgId, dept.getId())
                                        .orderByDesc(CsSystemSourceExt::getId).last("limit 1"));
                        if (null != sourceExts && !CollectionUtils.isEmpty(sourceExts)) {
                            csSystemAdmin.setSuperiorOrg(sourceExts.get(0).getSuperiorOrgName());
                            if (null != sourceExts.get(0).getSourceType() && sourceExts.get(0).getSourceType().contains("[") && sourceExts.get(0).getSourceType().contains("]")) {
                                csSystemAdmin.setSourceType(JSONArray.parseObject(sourceExts.get(0).getSourceType(), List.class));
                                if (!CollectionUtils.isEmpty(csSystemAdmin.getSourceType())) {
                                    List<String> sourceTypes = csSystemAdmin.getSourceType();
                                    if (null != sourceTypes && sourceTypes.size() > 0) {
                                        csSystemAdmin.getSourceType().forEach(type -> {
                                            if (type.contains("::")) {
                                                String[] split = type.split("::");
                                                List<String> typeList = Arrays.asList(split);
                                                for (String ty : typeList) {
                                                    CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(ty);
                                                    if (StringUtils.isNotEmpty(csSystemAdmin.getSourceTypeValue()) && null != csSystemSourceType) {
                                                        csSystemAdmin.setSourceTypeValue(csSystemAdmin.getSourceTypeValue() + csSystemSourceType.getName() + "，");
                                                    } else if (null != csSystemSourceType) {
                                                        csSystemAdmin.setSourceTypeValue(csSystemSourceType.getName() + "：");
                                                    }
                                                }
                                            } else {
                                                CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(type);
                                                if (StringUtils.isNotEmpty(csSystemAdmin.getSourceTypeValue()) && null != csSystemSourceType) {
                                                    csSystemAdmin.setSourceTypeValue(csSystemAdmin.getSourceTypeValue() + csSystemSourceType.getName() + "，");
                                                } else if (null != csSystemSourceType) {
                                                    csSystemAdmin.setSourceTypeValue(csSystemSourceType.getName() + "：");
                                                }
                                            }
                                        });
                                    }
                                }
                            } else if (null != sourceExts.get(0) && StringUtils.isNotEmpty(sourceExts.get(0).getSourceType())) {
                                csSystemAdmin.setSourceType(Arrays.asList(sourceExts.get(0).getSourceType().split(",")));
                                if (!CollectionUtils.isEmpty(csSystemAdmin.getSourceType())) {
                                    csSystemAdmin.getSourceType().forEach(type -> {

                                        if (type.contains("::")) {
                                            String[] split = type.split("::");
                                            List<String> typeList = Arrays.asList(split);
                                            for (String ty : typeList) {
                                                CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(ty);
                                                if (StringUtils.isNotEmpty(csSystemAdmin.getSourceTypeValue()) && null != csSystemSourceType) {
                                                    csSystemAdmin.setSourceTypeValue(csSystemAdmin.getSourceTypeValue() + csSystemSourceType.getName() + "，");
                                                } else if (null != csSystemSourceType) {
                                                    csSystemAdmin.setSourceTypeValue(csSystemSourceType.getName() + "：");
                                                }
                                            }
                                        } else {
                                            CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(type);
                                            if (null != csSystemSourceType && ("1000000010".equals(bean.getMenuID()) || "1000000012".equals(bean.getMenuID()))) {
                                                CsSystemSourceType parentSourceType = iCsSystemSourceTypeService.getById(csSystemSourceType.getParentId());

                                                csSystemAdmin.setSourceTypeValue(parentSourceType.getName() + csSystemSourceType.getName() + "，");
                                            } else if (null != csSystemSourceType) {

                                                csSystemAdmin.setSourceTypeValue(csSystemSourceType.getName() + "：");
                                            }
                                        }
                                    });
                                }
                            } else {
                                csSystemAdmin.setSourceType(new ArrayList<>());
                                csSystemAdmin.setSourceTypeValue("");
                            }

                            if (null != sourceExts.get(0).getSourceLevel()) {
                                CsSystemSourceLevelBean levelBean = JSONObject.parseObject(sourceExts.get(0).getSourceLevel(), CsSystemSourceLevelBean.class);
                                if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCountry()))
                                    sourceExt.setCountry(levelBean.getCountry());
                                if (null != levelBean && StringUtils.isNotEmpty(levelBean.getProvince()))
                                    sourceExt.setProvince(levelBean.getProvince());
                                if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCity()))
                                    sourceExt.setCity(levelBean.getCity());
                                if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCounty()))
                                    sourceExt.setCounty(levelBean.getCounty());
                                if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCityOrgId()))
                                    sourceExt.setCityOrgId(levelBean.getCityOrgId());
                                if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCityOrgName()))
                                    sourceExt.setCityOrgName(levelBean.getCityOrgName());
                                if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCountyOrgId()))
                                    sourceExt.setCountyOrgId(levelBean.getCountyOrgId());
                                if (null != levelBean && StringUtils.isNotEmpty(levelBean.getCountyOrgName()))
                                    sourceExt.setCountyOrgName(levelBean.getCountyOrgName());
                            }

                            //查询救援队伍的主要救援能力和辅助救援能力
                            if (null != bean.getMenuID() && "1000000010".equals(bean.getMenuID())) {
//                                String majorDuties = sourceExts.get(0).getMajorDuties();
//                                if (StringUtils.isNotEmpty(majorDuties)&&majorDuties.contains("[")&&majorDuties.contains("]")) {
//                                    csSystemAdmin.setMajorDuties(JSONObject.parseArray(majorDuties, String.class));
//                                }
                                if (StringUtils.isNotEmpty(sourceExts.get(0).getSecondaryDuties())) {
                                    csSystemAdmin.setSecondaryDuties(JSONObject.parseArray(sourceExts.get(0).getSecondaryDuties(), String.class));
                                }
                            }
                        }
                    }
                    csSystemAdmin.setSourceLevel(sourceExt);

                    if (StringUtils.isNotEmpty(bean.getOrgName())) {
                        if (dept.getValues().getName().contains(bean.getOrgName())) {
                            if (StringUtils.isNotEmpty(bean.getName())) {
                                if (csSystemAdmin.getName().contains(bean.getName())) {
                                    adminsAndDeptInfos.add(csSystemAdmin);
                                }
                            } else {
                                adminsAndDeptInfos.add(csSystemAdmin);
                            }
                        }
                    } else {
                        if (StringUtils.isNotEmpty(bean.getName())) {
                            if (csSystemAdmin.getName().contains(bean.getName())) {
                                adminsAndDeptInfos.add(csSystemAdmin);
                            }
                        } else {
                            adminsAndDeptInfos.add(csSystemAdmin);
                        }
                    }

                    String[] areaMenus = {"1000000003", "1000000004", "1000000005"};
                    List<String> areaMenusList = Arrays.asList(areaMenus);
                    if (areaMenusList.contains(bean.getMenuID())) {
                        adminsAndDeptInfos.forEach(dept2 -> {
                            Area area = areaService.getById(dept2.getAreaCode());
                            if (null != area) {
                                //在国家行政区划表格没有的数据默认为认为创建的行政区划,可以删除,删除状态为 2
                                dept2.setCreateType("1");
                            }
                        });
                    }
                }
            }
        }


        if (!CollectionUtils.isEmpty(adminsAndDeptInfos) && StringUtils.isNotEmpty(bean.getSourceId()) && ("1000000012".equals(bean.getMenuID()) || "1000000014".equals(bean.getMenuID()))) {
            List<CsSystemAdminAndOrgInfo> adminsAndDeptInfos2 = new ArrayList<>();
            List<String> subSourceTypeIds = new ArrayList<>();
            List<CsSystemSourceType> sourceTypes = new ArrayList<>();

            sourceTypes = iCsSystemSourceTypeService.list(new LambdaQueryWrapper<CsSystemSourceType>().eq(CsSystemSourceType::getId, bean.getSourceId()));

            if (!CollectionUtils.isEmpty(sourceTypes))
                sourceTypes.forEach(type -> {
                    subSourceTypeIds.add(type.getId());
                });
            for (CsSystemAdminAndOrgInfo adminAndOrgInfo : adminsAndDeptInfos) {
                if (null != adminAndOrgInfo.getSourceType() && ((!CollectionUtils.isEmpty(sourceTypes) && adminAndOrgInfo.getSourceType().contains(bean.getSourceId()))
                        || (!CollectionUtils.isEmpty(sourceTypes) && subSourceTypeIds.size() > 0 && !ObjectUtils.isEmpty(adminAndOrgInfo.getSourceType().get(adminAndOrgInfo.getSourceType().size() - 1)) && subSourceTypeIds.contains(adminAndOrgInfo.getSourceType().get(adminAndOrgInfo.getSourceType().size() - 1)))))

                    adminsAndDeptInfos2.add(adminAndOrgInfo);
            }
            return adminsAndDeptInfos2;
        } else {
            return adminsAndDeptInfos;
        }

    }

    @Override
    public String deleteCsSystemOrg(CsSystemOrgDeleteBean bean) throws ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        Map bodyParams = new HashMap<>();
        bodyParams.put("object_type", "DEPT");

        List<String> orgIdList = new ArrayList<>();
        //orgIdList.add(bean.getOrgId());

        /**
         * 先获取所有部门Ids
         */
        List<String> orgIds = new ArrayList<>();
        List<String> orgIds2 = new ArrayList<>();
        List<String> orgIds3 = new ArrayList<>();
        orgIds3.add(bean.getOrgId());

        if (!CollectionUtils.isEmpty(orgIds3) && orgIds3.size() > 0) {
            while (!CollectionUtils.isEmpty(orgIds3) && orgIds3.size() > 0) {
                for (String id : orgIds3) {
                    orgIds.add(id);
                    String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + id + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                    List<IDAASDeptResponse> listResponse2 = JSONArray.parseArray(str2, IDAASDeptResponse.class);
                    if (null != listResponse2 && !CollectionUtils.isEmpty(listResponse2)) {
                        for (IDAASDeptResponse deptResponse : listResponse2) {
                            orgIds2.add(deptResponse.getId());
                        }
                    }
                }
                orgIds3.clear();
                if (!CollectionUtils.isEmpty(orgIds)) {
                    orgIdList.addAll(orgIds);
                    orgIds.clear();
                }

                if (!CollectionUtils.isEmpty(orgIds2)) {
                    orgIds3.addAll(orgIds2);
                    orgIds2.clear();
                }

            }
        }

        List<UserInfo> userList = new ArrayList<>();
        Collections.reverse(orgIds);
        for (String id : orgIdList) {
            log.info(id);
            Map bodyParam = new HashMap();
            bodyParam.put("status", new ArrayList<>());


            List<String> orgId = new ArrayList<>();
            orgId.add(id);
            bodyParam.put("deptId", orgId);
            bodyParam.put("identityClassification", "defaultIdentityClassification");

            bodyParams.put("objectType", "USER");
            bodyParams.put("values", bodyParam);

            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/top_user/" + id + "/query?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str1 = HttpUtils.sendHttpPost(url1, (JSONObject) JSON.toJSON(bodyParams), headerParams);
            IDAASUserResponse object = JSONObject.parseObject(str1, IDAASUserResponse.class);
            userList.addAll(object.getData());
        }

        if (!CollectionUtils.isEmpty(userList)) {
            for (UserInfo userInfo : userList) {
                List<CsSystemAdmin> admin = adminService.list(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone, userInfo.getValues().getUsername()));
                if (null == admin || CollectionUtils.isEmpty(admin)) return "部门下存在用户,不允许删除";
            }
        }

        if (!CollectionUtils.isEmpty(userList)) {
            for (UserInfo userInfo : userList) {
                /**
                 * 删除用户前,先删除用户的管理权限
                 */
                if (StringUtils.isNotEmpty(userInfo.getValues().getUsername()))
                    if (adminService.count(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone, userInfo.getValues().getUsername())) > 0)
                        adminService.remove(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getPhone, userInfo.getValues().getUsername()));
                CsSystemDeleteBean deleteBean = new CsSystemDeleteBean();
                deleteBean.setId(userInfo.getId());
                userService.deleteCsSystemUser(deleteBean);
            }
        }
        for (String dept : orgIdList) {
            Map<String, String> deleteParam = new HashMap<>();
            deleteParam.put("status", "DISABLED");
            Map deleteParams = new HashMap();
            bodyParams.put("values", deleteParam);


            String url4 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/dept/" + dept + "/disable";
            String str4 = HttpUtils.sendHttpPut(url4, (JSONObject) JSON.toJSON(deleteParams), headerParams);
            service.remove(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getOrgId, dept));

            RescueTeam rescueTeam = rescueTeamService.getOne(new LambdaQueryWrapper<RescueTeam>()
                    .eq(RescueTeam::getDepId, dept));
            if (!ObjectUtils.isEmpty(rescueTeam)) {
                rescueTeam.setState("1");
                rescueTeamService.saveOrUpdate(rescueTeam);
                equipageMapper.deleteByteamId(rescueTeam.getId());

            }

            StoreInfo storeInfo = storeService.getOne(new LambdaQueryWrapper<StoreInfo>()
                    .eq(StoreInfo::getDepId, dept));
            if (!ObjectUtils.isEmpty(storeInfo)) {
                storeInfo.setState("1");
                storeService.saveOrUpdate(storeInfo);
                materialsMapper.deleteBystoreId(storeInfo.getId());
            }

            ProtectTargetInfo protectTargetInfo = protectTargetService.getOne(new LambdaQueryWrapper<ProtectTargetInfo>()
                    .eq(ProtectTargetInfo::getDepId, dept));
            if (!ObjectUtils.isEmpty(protectTargetInfo)) {
                protectTargetInfo.setState("1");
                protectTargetService.saveOrUpdate(protectTargetInfo);
            }

            RefugeInfo refugeInfo = refugeService.getOne(new LambdaQueryWrapper<RefugeInfo>()
                    .eq(RefugeInfo::getDepId, dept));
            if (!ObjectUtils.isEmpty(refugeInfo)) {
                refugeInfo.setState("1");
                refugeService.saveOrUpdate(refugeInfo);
            }
        }

        return "";
    }

    @Override
    public String udOrderCsSystemOrg(List<CsSystemUdOrderBean> beans) throws ParseException, JOSEException {

        if (!CollectionUtils.isEmpty(beans)) {
            HashMap<String, String> headerParams = new HashMap<>();
            headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());
            headerParams.put("Content-Type", "application/json");

            Map<String, Object> bodyParams = new HashMap();
            // bodyParams.put("object_type", "DEPT");
            beans.forEach(ud -> {
                Map<String, Integer> map = new HashMap();
                map.put("udOrder", Integer.valueOf(ud.getUdOrder()));
                String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + ud.getId();
                bodyParams.put("values", map);
                String str1 = HttpUtils.sendHttpPut(url1, (JSONObject) JSON.toJSON(bodyParams), headerParams);
                log.info(str1);
            });
        }
        return "";
    }

    @Override
    public CsSystemDeptResponse detailCsSystemOrg(CsSystemIDSelectBean bean) throws ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());
        headerParams.put("Content-Type", "application/json");

        Map<String, String> bodyParam = new HashMap();
        bodyParam.put("object_type", "DEPT");
        String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + bean.getId();
        String str1 = HttpUtils.httpGet(url1, bodyParam, headerParams);
        IDAASDeptResponse idaasDeptResponse = JSONObject.parseObject(str1, IDAASDeptResponse.class);
        CsSystemDeptResponse response = new CsSystemDeptResponse();
        if (null != idaasDeptResponse) {
            BeanUtils.copyProperties(idaasDeptResponse.getValues(), response);

            response.setId(idaasDeptResponse.getId());
            response.setSourceType("");
            if (StringUtils.isNotEmpty(response.getId())) {
                List<CsSystemSourceExt> sourceExts = csSystemSourceExtService.list(new LambdaQueryWrapper<CsSystemSourceExt>().eq(CsSystemSourceExt::getOrgId, bean.getId()));
                if (null != sourceExts && !CollectionUtils.isEmpty(sourceExts)) {
                    if (null != sourceExts.get(0).getSourceType() && sourceExts.get(0).getSourceType().contains("[") && sourceExts.get(0).getSourceType().contains("]")) {
                        List<String> sourcesTypes = JSONArray.parseObject(sourceExts.get(0).getSourceType(), List.class);
                        if (!CollectionUtils.isEmpty(sourcesTypes)) {
                            if (null != sourcesTypes && sourcesTypes.size() > 0) {
                                sourcesTypes.forEach(type -> {
                                    CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(type);
                                    if (StringUtils.isNotEmpty(response.getSourceType()) && null != csSystemSourceType) {
                                        response.setSourceType(response.getSourceType() + "," + csSystemSourceType.getName());
                                    } else if (null != csSystemSourceType) {
                                        response.setSourceType(csSystemSourceType.getName());
                                    }
                                });
                            }
                        }
                    } else if (null != sourceExts.get(0) && StringUtils.isNotEmpty(sourceExts.get(0).getSourceType())) {
                        List<String> source = Arrays.asList(sourceExts.get(0).getSourceType().split(","));
                        if (!CollectionUtils.isEmpty(source)) {
                            source.forEach(type -> {
                                CsSystemSourceType csSystemSourceType = iCsSystemSourceTypeService.getById(type);
                                if (null != csSystemSourceType && ("1000000010".equals(sourceExts.get(0).getMenuId()) || "1000000012".equals(sourceExts.get(0).getMenuId()))) {
                                    CsSystemSourceType parentSourceType = iCsSystemSourceTypeService.getById(csSystemSourceType.getParentId());

                                    response.setSourceType(parentSourceType.getName() + "," + csSystemSourceType.getName());
                                } else if (null != csSystemSourceType) {
                                    response.setSourceType(csSystemSourceType.getName());
                                }
                            });
                        }
                    } else {

                        response.setSourceType("");
                    }
                }
                if (null != sourceExts && !CollectionUtils.isEmpty(sourceExts)) {
                    response.setSourceLevel(JSONObject.parseObject(sourceExts.get(0).getSourceLevel(), CsSystemSourceLevelBean.class));
                    response.setSuperiorOrgId(sourceExts.get(0).getSuperiorOrgId());
                    response.setSuperiorOrgName(sourceExts.get(0).getSuperiorOrgName());
                }
            }
        }


        HashMap<String, String> headerParams2 = new HashMap<>();
        headerParams2.put("Content-Type", "application/json");

        HashMap bodyParams2 = new HashMap<>();
        Map bodyParam1 = new HashMap();
        bodyParam1.put("status", new ArrayList<>());
        bodyParam1.put("identityClassification", "defaultIdentityClassification");
        try {
            headerParams2.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (JOSEException e) {
            e.printStackTrace();
        }


       /* List<String> orgId = new ArrayList<>();
        orgId.add(bean.getId());
        bodyParam1.put("deptId", orgId);
        bodyParams2.put("values", bodyParam1);
        bodyParams2.put("objectType", "USER");

        String url2 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/top_user/" + bean.getId() + "/query?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName&need_child_depts=true";
        String str2 = HttpUtils.sendHttpPost(url2, (JSONObject) JSON.toJSON(bodyParams2), headerParams2);
        IDAASUserResponse object = JSONObject.parseObject(str2, IDAASUserResponse.class);*/
        response.setUserNumber(null == idaasDeptResponse.getValues().getUserNumber() ? 0 : idaasDeptResponse.getValues().getUserNumber());
        if (null == response.getMaxUserNumber())
            response.setMaxUserNumber(20);

        //获取资源的额外参数
        return response;
    }

    @Override
    public IDAASOrgEntity detailCsSystemBeyongOrg(CsSystemBeyongDeptSelectBean bean) throws ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());
        headerParams.put("Content-Type", "application/json");

        Map<String, String> bodyParam = new HashMap();
        bodyParam.put("object_type", "DEPT");
        String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + bean.getId() + "/traces";
        String str1 = HttpUtils.httpGet(url1, bodyParam, headerParams);
        IDAASDeptResponse info = deptService.getOrgInfoFromIDAASOrgList(str1, bean.getType());
        String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + info.getValues().getParentId();
        String str2 = HttpUtils.httpGet(url2, bodyParam, headerParams);
        IDAASDeptResponse idaasDeptResponse = JSONObject.parseObject(str2, IDAASDeptResponse.class);
        return idaasDeptResponse.getValues();
    }

    @Override
    public IDAASOrgEntity initOrg(CsSystemIDSelectBean bean) throws ParseException, JOSEException {

        Area area = areaService.getById(bean.getId());
        List<Area> cityAreas = new ArrayList<>();
        List<Area> countyAreas = new ArrayList<>();
        List<Area> townAreas = new ArrayList<>();
        if (null != area) {
            if ("Province".equals(area.getRemark())) {
                //省级行政区划编码
                List<Area> areas = areaService.list(new LambdaQueryWrapper<Area>().eq(Area::getParId, area.getId()));
                if (!CollectionUtils.isEmpty(areas)) {
                    cityAreas.addAll(areas);
                    for (Area a : cityAreas) {
                        List<Area> countyAreas2 = areaService.list(new LambdaQueryWrapper<Area>().eq(Area::getParId, a.getId()));
                        if (!CollectionUtils.isEmpty(countyAreas2)) {
                            countyAreas.addAll(countyAreas2);
                            for (Area a2 : countyAreas2) {
                                List<Area> townAreas3 = areaService.list(new LambdaQueryWrapper<Area>().eq(Area::getParId, a2.getId()));
                                if (!CollectionUtils.isEmpty(townAreas3)) {
                                    townAreas.addAll(townAreas3);
                                }
                            }
                        }

                    }
                }
                //初始化节点的方法
            } else if ("City".equals(area.getRemark())) {
                //市级别行政区划编
                cityAreas.add(area);
                List<Area> countyAreas1 = areaService.list(new LambdaQueryWrapper<Area>().eq(Area::getParId, area.getId()));
                if (!CollectionUtils.isEmpty(countyAreas1)) {
                    countyAreas.addAll(countyAreas1);
                    for (Area a : countyAreas1) {
                        List<Area> townAreas2 = areaService.list(new LambdaQueryWrapper<Area>().eq(Area::getParId, a.getId()));
                        if (!CollectionUtils.isEmpty(townAreas2)) {
                            townAreas.addAll(townAreas2);
                        }
                    }
                }
                //初始化节点的方法
            } else if ("County".equals(area.getRemark())) {
                //县级行政区划编码
                List<Area> townAreas1 = areaService.list(new LambdaQueryWrapper<Area>().eq(Area::getParId, area.getId()));
                if (!CollectionUtils.isEmpty(townAreas1)) {
                    townAreas.addAll(townAreas1);
                }

            } else if (("town").equals(area.getRemark())) {
                //村镇级行政区划编码
                //initOrgTreeByArea(area, area.getName);

                //初始化节点的方法
            } else {

            }

            //初始化所有的盟市节点
            if (!CollectionUtils.isEmpty(cityAreas))
                cityAreas.forEach(city -> {
                    try {
                        initOrgTreeByArea(city, area.getName());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    } catch (JOSEException e) {
                        e.printStackTrace();
                    }
                });

            //初始化所有的旗县节点
            if (!CollectionUtils.isEmpty(countyAreas))
                countyAreas.forEach(county -> {
                    try {
                        initOrgTreeByArea(county, "");
                    } catch (ParseException e) {
                        e.printStackTrace();
                    } catch (JOSEException e) {
                        e.printStackTrace();
                    }
                });

            //初始化所有的乡镇节点
            if (!CollectionUtils.isEmpty(townAreas))
                townAreas.forEach(town -> {
                    try {
                        Area county = areaService.getById(town.getParId());
                        initOrgTreeByArea(town, areaService.getById(county.getParId()).getName());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    } catch (JOSEException e) {
                        e.printStackTrace();
                    }
                });
        }

        return null;
    }


    @Override
    public void initProvinceInstitution(CsSystemIDSelectBean bean) throws ParseException, JOSEException {
        Area area = areaService.getById(bean.getId());

        if (null != area) {
            if (null != area) {
                HashMap<String, String> headerParams = new HashMap<>();
                headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

                HashMap<String, String> bodyParams = new HashMap<>();
                bodyParams.put("object_type", "DEPT");

                String url = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + "dp-10aa1969bd094b05bdfa764126fc6210" + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str = HttpUtils.httpGet(url, bodyParams, headerParams);
                IDAASDeptResponse unenableCityDept = getOrgInfoFromIDAASOrgList(str, "待启用节点");
                IDAASOrgEntity orgEntity = null;
                if (null == unenableCityDept || StringUtils.isEmpty(unenableCityDept.getId())) {
                    CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                    createBean.setOrgName(area.getName());
                    createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                    createBean.setUdOrder(Integer.valueOf(StringUtils.substring(area.getId(), 3, 5)));
                    orgEntity = createOrgToIDAAS(createBean, "待启用节点", "dp-10aa1969bd094b05bdfa764126fc6210");
                } else {
                    orgEntity = unenableCityDept.getValues();
                }
                String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + orgEntity.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                IDAASOrgEntity institutionDept = getOrgInfoFromIDAASOrgList(str2, "成员单位").getValues();
                if (null == institutionDept || StringUtils.isEmpty(institutionDept.getId())) {
                    CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                    createBean.setOrgName(area.getName());
                    createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                    createBean.setUdOrder(Integer.valueOf(StringUtils.substring(area.getId(), 3, 5)));
                    institutionDept = createOrgToIDAAS(createBean, "成员单位", orgEntity.getId());

                }
                if (null != institutionDept && StringUtils.isNotEmpty(institutionDept.getId())) {
                    List<CsSystemMenuOrgInstitutionTemplate> list = templateService.list(new LambdaQueryWrapper<CsSystemMenuOrgInstitutionTemplate>().eq(CsSystemMenuOrgInstitutionTemplate::getAreaLevel, area.getRemark()));
                    if (!CollectionUtils.isEmpty(list)) {
                        CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                        for (CsSystemMenuOrgInstitutionTemplate tem : list) {
                            createBean.setOrgName(tem.getOrgName());
                            createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                            createBean.setUdOrder(tem.getUdOrder());
                            try {
                                IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", institutionDept.getId());
                            } catch (ParseException e) {
                                e.printStackTrace();
                            } catch (JOSEException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }

            }
        }

    }

    @Override
    public void initInstitution(CsSystemIDSelectBean bean) throws ParseException, JOSEException {
        Area area = areaService.getById(bean.getId());

        if (null != area) {
            List<Area> areas = areaService.list(new LambdaQueryWrapper<Area>().eq(Area::getParId, area.getId()));
            if (!CollectionUtils.isEmpty(areas)) {
                HashMap<String, String> headerParams = new HashMap<>();
                headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

                HashMap<String, String> bodyParams = new HashMap<>();
                bodyParams.put("object_type", "DEPT");

                String url = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + "dp-10aa1969bd094b05bdfa764126fc6210" + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str = HttpUtils.httpGet(url, bodyParams, headerParams);
                IDAASDeptResponse unenableCityDept = getOrgInfoFromIDAASOrgList(str, "待启用节点");
                IDAASOrgEntity orgEntity = null;
                if (null == unenableCityDept || StringUtils.isEmpty(unenableCityDept.getId())) {
                    CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                    createBean.setOrgName(area.getName());
                    createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                    createBean.setUdOrder(Integer.valueOf(StringUtils.substring(area.getId(), 3, 5)));
                    orgEntity = createOrgToIDAAS(createBean, "待启用节点", "dp-10aa1969bd094b05bdfa764126fc6210");
                } else {
                    orgEntity = unenableCityDept.getValues();
                }
                String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + orgEntity.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                IDAASDeptResponse cityDept = getOrgInfoFromIDAASOrgList(str2, "盟市指挥体系");

                if (null != cityDept && StringUtils.isNotEmpty(cityDept.getId())) {

                    for (Area a : areas) {
                        if (Long.valueOf(a.getId()) > 150800000000l) {

                            String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + cityDept.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                            String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);
                            IDAASDeptResponse cityDeptDetail = getOrgInfoFromIDAASOrgList(str3, a.getName());
                            if (null != cityDeptDetail && StringUtils.isNotEmpty(cityDeptDetail.getId())) {
                                String url4 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + cityDeptDetail.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                                String str4 = HttpUtils.httpGet(url4, bodyParams, headerParams);
                                IDAASDeptResponse countyDept = getOrgInfoFromIDAASOrgList(str4, "旗县指挥体系");
                                if (null != countyDept && StringUtils.isNotEmpty(countyDept.getId())) {
                                    List<Area> countyAreas = areaService.list(new LambdaQueryWrapper<Area>().eq(Area::getParId, a.getId()));
                                    if (!CollectionUtils.isEmpty(countyAreas)) {
                                        countyAreas.forEach(county -> {
                                            String url5 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + countyDept.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                                            String str5 = HttpUtils.httpGet(url5, bodyParams, headerParams);
                                            IDAASDeptResponse countyDeptDetail = getOrgInfoFromIDAASOrgList(str5, county.getName());

                                            if (null != countyDeptDetail && StringUtils.isNotEmpty(countyDeptDetail.getId())) {
                                                String url6 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + countyDeptDetail.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                                                String str6 = HttpUtils.httpGet(url6, bodyParams, headerParams);
                                                IDAASDeptResponse institutionDept = getOrgInfoFromIDAASOrgList(str6, "成员单位");
                                                if (null != institutionDept && StringUtils.isNotEmpty(institutionDept.getId())) {
                                                    List<CsSystemMenuOrgInstitutionTemplate> list = templateService.list(new LambdaQueryWrapper<CsSystemMenuOrgInstitutionTemplate>().eq(CsSystemMenuOrgInstitutionTemplate::getAreaLevel, county.getRemark()));
                                                    if (!CollectionUtils.isEmpty(list)) {
                                                        CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                                                        list.forEach(t -> {
                                                            createBean.setOrgName(t.getOrgName());
                                                            createBean.setAreaCode(StringUtils.substring(a.getId(), 0, 9));
                                                            createBean.setUdOrder(t.getUdOrder());
                                                            try {
                                                                IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", institutionDept.getId());
                                                            } catch (ParseException e) {
                                                                e.printStackTrace();
                                                            } catch (JOSEException e) {
                                                                e.printStackTrace();
                                                            }
                                                        });
                                                    }
                                                }
                                            }
                                        });

                                    }

                                }
                            }
                        }

                    }

                }

            }

        }


    }

    @Override
    public void initDeleteOrg(CsSystemOrgInitDeleteBean bean) throws ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        Map bodyParams = new HashMap<>();
        bodyParams.put("object_type", "DEPT");

        List<String> orgIdList = new ArrayList<>();

        /**
         * 先获取所有部门Ids
         */
        List<String> orgIds = new ArrayList<>();
        List<String> orgIds2 = new ArrayList<>();
        List<String> orgIds3 = new ArrayList<>();
        orgIds3.add(bean.getId());

        if (!CollectionUtils.isEmpty(orgIds3) && orgIds3.size() > 0) {
            do {
                for (String id : orgIds3) {
                    orgIds.add(id);
                    String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + id + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                    List<IDAASDeptResponse> listResponse2 = JSONArray.parseArray(str2, IDAASDeptResponse.class);
                    if (null != listResponse2 && !CollectionUtils.isEmpty(listResponse2)) {
                        for (IDAASDeptResponse deptResponse : listResponse2) {
                            orgIds2.add(deptResponse.getId());
                        }
                    }
                }
                orgIds3.clear();
                if (!CollectionUtils.isEmpty(orgIds)) {
                    orgIdList.addAll(orgIds);
                    orgIds.clear();
                }

                if (!CollectionUtils.isEmpty(orgIds2)) {
                    orgIds3.addAll(orgIds2);
                    orgIds2.clear();
                }

            } while (!CollectionUtils.isEmpty(orgIds3));
        }
        List<UserInfo> userList = new ArrayList<>();
        Collections.reverse(orgIdList);
        for (String id : orgIdList) {
            log.info(id);
            Map bodyParam = new HashMap();
            bodyParam.put("status", new ArrayList<>());


            List<String> orgId = new ArrayList<>();
            orgId.add(id);
            bodyParam.put("deptId", orgId);
            bodyParam.put("identityClassification", "defaultIdentityClassification");

            bodyParams.put("objectType", "USER");
            bodyParams.put("values", bodyParam);

            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/top_user/" + id + "/query?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str1 = HttpUtils.sendHttpPost(url1, (JSONObject) JSON.toJSON(bodyParams), headerParams);
            IDAASUserResponse object = JSONObject.parseObject(str1, IDAASUserResponse.class);
            userList.addAll(object.getData());
        }

        if (!CollectionUtils.isEmpty(userList)) {
            for (UserInfo userInfo : userList) {
                CsSystemDeleteBean deleteBean = new CsSystemDeleteBean();
                deleteBean.setId(userInfo.getId());
                userService.deleteCsSystemUser(deleteBean);
            }
        }

        for (String dept : orgIdList) {
            Map<String, String> deleteParam = new HashMap<>();
            deleteParam.put("status", "DISABLED");
            Map deleteParams = new HashMap();
            bodyParams.put("values", deleteParam);

            String url4 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/dept/" + dept + "/disable";

            if (bean.getType() == 1) {
                String str4 = HttpUtils.sendHttpPut(url4, (JSONObject) JSON.toJSON(deleteParams), headerParams);
            } else if (bean.getType() == 2) {
                String clientPostRes = HttpUtils.httpDelete("http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + dept,
                        new HashMap<>(), headerParams);
            }
        }
    }

    @Override
    public List<IDAASOrgEntity> selectTeamLevel(Area area) throws ParseException, JOSEException {
        List<IDAASOrgEntity> resList = new ArrayList<>();

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "Bearer " + NMGYJTIDAASTokenUtils.getToken());

        Map<String, String> bodyParams = new HashMap();
        bodyParams.put("object_type", "DEPT");
        bodyParams.put("keywords", area.getName());

        String clientPostRes = HttpUtils.httpGet("http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/search", bodyParams, headerParams);

        IDAASDeptResponse deptResponse = null;

        if (null != clientPostRes) {
            if (StringUtils.isNotEmpty(clientPostRes) && clientPostRes.contains(area.getName())) {
                IDAASDeptListResponse listResponse = JSONObject.parseObject(clientPostRes, IDAASDeptListResponse.class);
                if (!CollectionUtils.isEmpty(listResponse.getData())) {
                    for (IDAASDeptResponse dept : listResponse.getData()) {
                        if (area.getName().equals(dept.getValues().getName())) {
                            deptResponse = dept;
                            break;
                        }
                    }
                }
            }
            if (null != deptResponse) {
                String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + deptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                IDAASDeptResponse interDeptResponse = deptService.getOrgInfoFromIDAASOrgList(str2, "成员单位");
                String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + interDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);

                if (null != clientPostRes) {
                    List<IDAASDeptResponse> deptList = JSONArray.parseArray(str3, IDAASDeptResponse.class);
                    if (null != deptList && !CollectionUtils.isEmpty(deptList)) {
                        for (IDAASDeptResponse dept : deptList) {
                            String url4 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + dept.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                            String str4 = HttpUtils.httpGet(url4, bodyParams, headerParams);
                            if (str4.contains("救援队伍")) {
                                dept.getValues().setId(dept.getId());
                                resList.add(dept.getValues());
                            }
                        }

                    }
                }
            }
        }

        return resList;
    }


    void initOrgTreeByArea(Area area, String cityName) throws ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        HashMap<String, String> bodyParams = new HashMap<>();
        bodyParams.put("object_type", "DEPT");

        String url = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + "dp-10aa1969bd094b05bdfa764126fc6210" + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
        String str = HttpUtils.httpGet(url, bodyParams, headerParams);
        IDAASDeptResponse unenableCityDept = getOrgInfoFromIDAASOrgList(str, "待启用节点");
        IDAASOrgEntity orgEntity = null;
        if (null == unenableCityDept || StringUtils.isEmpty(unenableCityDept.getId())) {
            CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
            createBean.setOrgName(area.getName());
            createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
            createBean.setUdOrder(Integer.valueOf(StringUtils.substring(area.getId(), 3, 5)));
            orgEntity = createOrgToIDAAS(createBean, "待启用节点", "dp-10aa1969bd094b05bdfa764126fc6210");
        } else {
            orgEntity = unenableCityDept.getValues();
        }

        if ("City".equals(area.getRemark())) {
            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + orgEntity.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
            IDAASDeptResponse cityDept = getOrgInfoFromIDAASOrgList(str1, "盟市指挥体系");
            if (null != cityDept && StringUtils.isNotEmpty(cityDept.getId())) {
                String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + cityDept.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                IDAASDeptResponse cityDeptDetail = getOrgInfoFromIDAASOrgList(str2, area.getName());
                if (null != cityDeptDetail && StringUtils.isNotEmpty(cityDeptDetail.getId())) {

                    String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + cityDeptDetail.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);

                    CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                    if (!str3.contains("党委领导")) {
                        createBean.setOrgName("党委领导");
                        createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                        createBean.setUdOrder(1);
                        IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", cityDeptDetail.getId());

                    }
                    if (!str3.contains("政府领导")) {
                        createBean.setOrgName("政府领导");
                        createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                        createBean.setUdOrder(2);
                        IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", cityDeptDetail.getId());

                    }
                    if (!str3.contains("成员单位")) {
                        createBean.setOrgName("成员单位");
                        createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                        createBean.setUdOrder(3);
                        IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", cityDeptDetail.getId());
                    }
                    if (!str3.contains("旗县指挥体系")) {
                        createBean.setOrgName("旗县指挥体系");
                        createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                        createBean.setUdOrder(4);
                        IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", cityDeptDetail.getId());
                    }
                    if (!str3.contains("管理员")) {
                        createBean.setOrgName("管理员");
                        createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                        createBean.setUdOrder(5);
                        IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", cityDeptDetail.getId());
                    }

                } else {
                    CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                    createBean.setOrgName(area.getName());
                    createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                    createBean.setUdOrder(Integer.valueOf(StringUtils.substring(area.getId(), 2, 4)));
                    createOrgToIDAAS(createBean, "", cityDept.getId());
                    initOrgTreeByArea(area, cityName);
                }

            } else {
                //创建盟市指挥体系
                CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                createBean.setOrgName("盟市指挥体系");
                createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                createBean.setUdOrder(4);
                createOrgToIDAAS(createBean, "", unenableCityDept.getId());
                initOrgTreeByArea(area, cityName);
            }

        } else if ("County".equals(area.getRemark())) {

            Area city = areaService.getById(area.getParId());
            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + "dp-420059454c644cea918f86b5deb78379" + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
            IDAASDeptResponse cityDept = getOrgInfoFromIDAASOrgList(str1, city.getName());

            if (null != cityDept && StringUtils.isNotEmpty(cityDept.getId())) {
                if (!ObjectUtils.isEmpty(cityDept) && StringUtils.isNotEmpty(cityDept.getId())) {
                    log.info(JSONObject.toJSONString(cityDept));
                    String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + cityDept.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                    IDAASDeptResponse countyDept = getOrgInfoFromIDAASOrgList(str2, "旗县指挥体系");
                    if (null != countyDept && StringUtils.isNotEmpty(countyDept.getId())) {
                        String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + countyDept.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                        String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);
                        IDAASDeptResponse countyDeptDetail = getOrgInfoFromIDAASOrgList(str3, area.getName());

                        if (null != countyDeptDetail && StringUtils.isNotEmpty(countyDeptDetail.getId())) {

                            CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                            if (!str3.contains("党委领导")) {
                                createBean.setOrgName("党委领导");
                                createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                                createBean.setUdOrder(1);
                                IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", countyDeptDetail.getId());

                            }
                            if (!str3.contains("政府领导")) {
                                createBean.setOrgName("政府领导");
                                createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                                createBean.setUdOrder(2);
                                IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", countyDeptDetail.getId());

                            }
                            if (!str3.contains("成员单位")) {
                                createBean.setOrgName("成员单位");
                                createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                                createBean.setUdOrder(3);
                                IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", countyDeptDetail.getId());
                            }
                            if (!str3.contains("乡镇指挥体系")) {
                                createBean.setOrgName("乡镇指挥体系");
                                createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                                createBean.setUdOrder(4);
                                IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", countyDeptDetail.getId());
                            }
                            if (!str3.contains("管理员")) {
                                createBean.setOrgName("管理员");
                                createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                                createBean.setUdOrder(5);
                                IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", countyDeptDetail.getId());
                            }

                        } else {
                            CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                            createBean.setOrgName(area.getName());
                            createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                            createBean.setUdOrder(Integer.valueOf(StringUtils.substring(area.getId(), 4, 6)));
                            createOrgToIDAAS(createBean, "", countyDept.getId());
                            initOrgTreeByArea(area, cityName);
                        }

                    } else {
                        CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                        createBean.setOrgName(area.getName());
                        createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                        createBean.setUdOrder(Integer.valueOf(StringUtils.substring(area.getId(), 2, 4)));
                        createOrgToIDAAS(createBean, "旗县指挥体系", cityDept.getId());
                        initOrgTreeByArea(area, cityName);
                    }

                } else {
                }
            } else {

            }

        } else if (("Town").equals(area.getRemark())) {

            String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + "dp-420059454c644cea918f86b5deb78379" + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
            String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
            IDAASDeptResponse cityDept = getOrgInfoFromIDAASOrgList(str1, cityName);

            if (null != cityDept && !StringUtils.isEmpty(cityDept.getId())) {

                String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + cityDept.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                IDAASDeptResponse countyDept = getOrgInfoFromIDAASOrgList(str2, "旗县指挥体系");

                if (null != countyDept && !StringUtils.isEmpty(countyDept.getId())) {

                    Area county = areaService.getById(area.getParId());
                    String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + countyDept.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str3 = HttpUtils.httpGet(url3, bodyParams, headerParams);
                    IDAASDeptResponse countyDeptDetail = getOrgInfoFromIDAASOrgList(str3, county.getName());

                    if (null != countyDeptDetail && StringUtils.isNotEmpty(countyDeptDetail.getId())) {

                        String url4 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + countyDeptDetail.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                        String str4 = HttpUtils.httpGet(url4, bodyParams, headerParams);
                        IDAASDeptResponse townDept = getOrgInfoFromIDAASOrgList(str4, "乡镇指挥体系");
                        if (null != townDept && StringUtils.isNotEmpty(townDept.getId())) {
                            String url5 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + townDept.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                            String str5 = HttpUtils.httpGet(url5, bodyParams, headerParams);

                            IDAASDeptResponse townDeptDeptDetail = getOrgInfoFromIDAASOrgList(str5, area.getName());

                            if (null != townDeptDeptDetail && StringUtils.isNotEmpty(townDeptDeptDetail.getId())) {

                                CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                                if (!str3.contains("内设机构")) {
                                    createBean.setOrgName("内设机构");
                                    createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                                    createBean.setUdOrder(1);
                                    IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", townDeptDeptDetail.getId());

                                }
                                if (!str3.contains("指挥体系成员")) {
                                    createBean.setOrgName("指挥体系成员");
                                    createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                                    createBean.setUdOrder(2);
                                    IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", townDeptDeptDetail.getId());

                                }
                                if (!str3.contains("嘎查、村、屯")) {
                                    createBean.setOrgName("嘎查、村、屯");
                                    createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                                    createBean.setUdOrder(3);
                                    IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", townDeptDeptDetail.getId());
                                }

                            } else {
                                CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                                createBean.setOrgName(area.getName());
                                createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                                createBean.setUdOrder(Integer.valueOf(StringUtils.substring(area.getId(), 6, 9)));
                                IDAASOrgEntity orgToIDAAS = createOrgToIDAAS(createBean, "", townDept.getId());
                                if (null != orgToIDAAS && StringUtils.isNotEmpty(orgToIDAAS.getId()))
                                    initOrgTreeByArea(area, cityName);
                            }

                        } else {
                            CsSystemOrgCreateBean createBean = new CsSystemOrgCreateBean();
                            createBean.setOrgName(area.getName());
                            createBean.setAreaCode(StringUtils.substring(area.getId(), 0, 9));
                            createBean.setUdOrder(Integer.valueOf(StringUtils.substring(area.getId(), 2, 4)));
                            createOrgToIDAAS(createBean, "乡镇指挥体系", countyDeptDetail.getId());
                            initOrgTreeByArea(area, cityName);

                        }
                    }


                }
            }
        } else {

        }
    }

    /**
     * 预设内设机构
     */
    @Override
    public void preSetOffices(CsSystemOrgCreateBean dept, String orgId) throws ParseException, JOSEException {

        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        HashMap<String, String> bodyParams = new HashMap<>();
        bodyParams.put("object_type", "DEPT");
        if (!CollectionUtils.isEmpty(dept.getPreSetOrgInfos()) && JSONObject.toJSONString(dept.getPreSetOrgInfos()).contains("1000000007")) {
            for (CsSystemOrgPreSetBean preSetBean : dept.getPreSetOrgInfos()) {
                if ("1000000007".equals(preSetBean.getId()) && null != preSetBean.getOrgChildren() && preSetBean.getOrgChildren().size() > 0) {
                    //获取子部门相关信息:/api/v1/departments/{department_id}/children
                    String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + orgId + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str1 = HttpUtils.httpGet(url1, bodyParams, headerParams);
                    String interDeptId = null;
                    IDAASOrgEntity idaasOrg = null;
                    IDAASDeptResponse interDeptResponse = null;
                    if (!str1.contains("内设机构")) {
                        idaasOrg = createOrgToIDAAS(dept, "内设机构", orgId);
                        interDeptId = idaasOrg.getId();
                    } else {
                        /**
                         * 返回的子部门有内设机构就不用创建,直接获取相关内设机构信息,创建部门
                         */
                        interDeptResponse = getOrgInfoFromIDAASOrgList(str1, "内设机构");
                        interDeptId = interDeptResponse.getId();
                    }

                    String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + interDeptId + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);

                    if (!CollectionUtils.isEmpty(preSetBean.getOrgChildren())) {
                        for (CsSystemOrgItemPreSetBean office : preSetBean.getOrgChildren()) {
                            if (!str2.contains(office.getName())) {
                                dept.setMaxUserNumber(office.getMaxUserNumber());
                                dept.setMenuID("1000000007");
                                createOrgToIDAAS(dept, office.getName(), interDeptId);
                            } else {
                                IDAASDeptResponse deptResponse = getOrgInfoFromIDAASOrgList(str2, office.getName());
                                Map<String, Object> map = new HashMap();
                                map.put("name", office.getName());
                                map.put("maxUserNumber", office.getMaxUserNumber());
                                Map updateBodyParams = new HashMap<>();
                                String url3 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + deptResponse.getId();
                                updateBodyParams.put("values", map);
                                String str3 = HttpUtils.sendHttpPut(url3, (JSONObject) JSON.toJSON(updateBodyParams), headerParams);
                            }
                        }
                    }
                }
            }
        }
        return;
    }

    /***
     * todo 加一个定时器,实现机构/部门人数更新
     * @throws ParseException
     * @throws JOSEException
     */
    @Scheduled(cron = "0 0 1 * * ?")
    @Override
    public void updateOrgUserNumber() throws ParseException, JOSEException {

        String rootOrgId = "dp-10aa1969bd094b05bdfa764126fc6210";
        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Content-Type", "application/json");
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());

        Map bodyParams = new HashMap<>();
        bodyParams.put("object_type", "DEPT");

        List<String> orgIdList = new ArrayList<>();
        //orgIdList.add(bean.getOrgId());

        /**
         * 先获取所有部门Ids
         */
        List<String> orgIds = new ArrayList<>();
        List<String> orgIds2 = new ArrayList<>();
        List<String> orgIds3 = new ArrayList<>();
        orgIds3.add(rootOrgId);

        if (!CollectionUtils.isEmpty(orgIds3) && orgIds3.size() > 0) {
            while (!CollectionUtils.isEmpty(orgIds3) && orgIds3.size() > 0) {
                for (String id : orgIds3) {
                    orgIds.add(id);
                    String url2 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + id + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                    String str2 = HttpUtils.httpGet(url2, bodyParams, headerParams);
                    List<IDAASDeptResponse> listResponse2 = JSONArray.parseArray(str2, IDAASDeptResponse.class);
                    if (null != listResponse2 && !CollectionUtils.isEmpty(listResponse2)) {
                        for (IDAASDeptResponse deptResponse : listResponse2) {
                            orgIds2.add(deptResponse.getId());
                        }
                    }
                }
                orgIds3.clear();
                if (!CollectionUtils.isEmpty(orgIds)) {
                    orgIdList.addAll(orgIds);
                    orgIds.clear();
                }

                if (!CollectionUtils.isEmpty(orgIds2)) {
                    orgIds3.addAll(orgIds2);
                    orgIds2.clear();
                }
                log.info(">>>>>>获取成员单位组织id中....");
            }
        }

        for (String dept : orgIdList) {

            HashMap bodyParams3 = new HashMap<>();
            Map<Object, Object> objectMap = new HashMap<>();
            objectMap.put("status", new ArrayList<>());
            objectMap.put("identityClassification", "defaultIdentityClassification");
            bodyParams3.put("objectType", "USER");
            List<String> idList = new ArrayList<>();
            idList.add(dept);
            objectMap.put("deptId", idList);
            bodyParams3.put("values", objectMap);
            String userNumberUrl = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/top_user/" + dept + "/query?page_index=0&page_size=10&order_by=_udOrder&order_by=_displayName&need_child_depts=true";
            String str2 = HttpUtils.sendHttpPost(userNumberUrl, (JSONObject) JSON.toJSON(bodyParams3), headerParams);

            IDAASUserResponse object = JSONObject.parseObject(str2, IDAASUserResponse.class);
            Integer userNumber = null == object.getTotal() ? 0 : object.getTotal();

            Map<String, Object> map = new HashMap();
            map.put("userNumber", userNumber);
            Map updateBodyParams = new HashMap<>();
            String url4 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + dept;
            updateBodyParams.put("values", map);
            String str4 = HttpUtils.sendHttpPut(url4, (JSONObject) JSON.toJSON(updateBodyParams), headerParams);

        }

        return;

    }


    public List<CsSystemAdminAndOrgInfo> selectOrgResetDetail(CsSystemOrgSelectBean bean) throws ParseException, JOSEException {
      /*  UserInfo loginAdminInfo = IDAASUserUtils.selectUserInfoFromIDAASByOpenIdV2(bean.getCreatedBy());

        if (ObjectUtils.isEmpty(loginAdminInfo)) {
            log.error("管理员账号非法,查询失败,查询信息如下:{}", bean);
            throw new BizException("查询统一认证用户失败,请联系系统管理员!");
        }*/
        CsSystemAdmin admin = adminService.getOne(new LambdaQueryWrapper<CsSystemAdmin>().eq(CsSystemAdmin::getOrgId, bean.getOrgId()).orderByDesc(CsSystemAdmin::getUpdatedTime).last("limit 1"));

        if (ObjectUtils.isEmpty(admin)) {
            return new ArrayList<>();
        }

        List<CsSystemAdminAndOrgInfo> adminsAndDeptInfos = new ArrayList<>();


        HashMap<String, String> headerParams = new HashMap<>();
        headerParams.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());
        headerParams.put("Content-Type", "application/json");

        Map<String, String> bodyParam = new HashMap();
        bodyParam.put("object_type", "DEPT");
        String url1 = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + bean.getOrgId();
        String str1 = HttpUtils.httpGet(url1, bodyParam, headerParams);
        IDAASDeptResponse idaasDeptResponse = JSONObject.parseObject(str1, IDAASDeptResponse.class);

        if (null != idaasDeptResponse && StringUtils.isNotEmpty(idaasDeptResponse.getId())) {

            HashMap<String, String> headerParams2 = new HashMap<>();
            headerParams2.put("Content-Type", "application/json");
            try {
                headerParams2.put("Authorization", "bearer " + NMGYJTIDAASTokenUtils.getToken());
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (JOSEException e) {
                e.printStackTrace();
            }
            if (!"管理员".equals(idaasDeptResponse.getValues().getName()) && "ENABLED".equals(idaasDeptResponse.getValues().getStatus())) {

                CsSystemAdminAndOrgInfo csSystemAdmin = new CsSystemAdminAndOrgInfo();
                   /* if ("1000000006".equals(bean.getMenuID())) {
                        HashMap bodyParams3 = new HashMap<>();
                        Map<Object, Object> objectMap = new HashMap<>();
                        objectMap.put("status", new ArrayList<>());
                        objectMap.put("identityClassification", "defaultIdentityClassification");
                        bodyParams3.put("objectType", "USER");
                        List<String> idList = new ArrayList<>();
                        idList.add(dept.getId());
                        objectMap.put("deptId", idList);
                        bodyParams3.put("values", objectMap);
                        String userNumberUrl = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/top_user/" + dept.getId() + "/query?page_index=0&page_size=10&order_by=_udOrder&order_by=_displayName&need_child_depts=true";
                        String str2 = HttpUtils.sendHttpPost(userNumberUrl, (JSONObject) JSON.toJSON(bodyParams3), headerParams2);

                        IDAASUserResponse object = JSONObject.parseObject(str2, IDAASUserResponse.class);
                        csSystemAdmin.setUserNumber(object.getTotal());
                    }*/
                List<CsSystemAdmin> admins = service.list(
                        CsSystemAdmin.gw().eq(CsSystemAdmin::getOrgId, idaasDeptResponse.getId()));
                if (CollectionUtils.isEmpty(admins)) {
                    csSystemAdmin.setOrgName(idaasDeptResponse.getValues().getName());
                    csSystemAdmin.setOrgId(idaasDeptResponse.getId());
                    csSystemAdmin.setSuperiorOrg(admin.getOrgId());
                    csSystemAdmin.setUdOrder(Integer.valueOf(idaasDeptResponse.getValues().getUdOrder()));
                    csSystemAdmin.setName("");
                    csSystemAdmin.setJob("");
                    csSystemAdmin.setPhone("");
                    csSystemAdmin.setOffice("");
                    csSystemAdmin.setId("");
                    csSystemAdmin.setMaxUserNumber(idaasDeptResponse.getValues().getMaxUserNumber());
                    csSystemAdmin.setUserNumber(idaasDeptResponse.getValues().getUserNumber());

                    if ("1000000007".equals(bean.getMenuID())) {
                        csSystemAdmin.setOffice(idaasDeptResponse.getValues().getName());
                    }
                } else {
                    BeanUtils.copyProperties(admins.get(admins.size() - 1), csSystemAdmin);
                    csSystemAdmin.setOrgName(idaasDeptResponse.getValues().getName());
                    csSystemAdmin.setMaxUserNumber(idaasDeptResponse.getValues().getMaxUserNumber());
                    csSystemAdmin.setUserNumber(idaasDeptResponse.getValues().getUserNumber());

                    if ("1000000007".equals(bean.getMenuID())) {
                        csSystemAdmin.setOffice(idaasDeptResponse.getValues().getName());
                    }
                    //获取机构的预设成员单位数据
                    String permissionStr = csSystemAdmin.getMenuPermission().replace("::", "");
                    permissionStr = permissionStr.replace(":", ",");
                    if (StringUtils.isNotEmpty(permissionStr)) {
                        List<String> permissionList = Arrays.asList(permissionStr.split(","));
                        if (!CollectionUtils.isEmpty(permissionList)) {
                            List<CsSystemOrgPreSetBean> preSetOrgInfos = new ArrayList<>();

                            for (String p : permissionList) {
                                CsSystemOrgPreSetBean preSetBean = new CsSystemOrgPreSetBean();

                                if ("1000000007".equals(p)) {

                                    List<IDAASDeptResponse> responseList = new ArrayList<>();
                                    if (!"1000000007".equals(bean.getMenuID())) {
                                        String preSetOfficeUrl = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + idaasDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName";
                                        String preSetOfficeStr = HttpUtils.httpGet(preSetOfficeUrl, bodyParam, headerParams);
                                        IDAASDeptResponse interDeptResponse = deptService.getOrgInfoFromIDAASOrgList(preSetOfficeStr, "内设机构");

                                        String preSetOfficeDetailUrl = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + interDeptResponse.getId() + "/children?page_index=0&page_size=200&order_by=_regionCode&order_by=_udOrder&order_by=_createdOn";
                                        String preSetOfficeStrDetail = HttpUtils.httpGet(preSetOfficeDetailUrl, bodyParam, headerParams);
                                        responseList = JSONArray.parseArray(preSetOfficeStrDetail, IDAASDeptResponse.class);
                                    } else {

                                        String preSetOfficeUrl = "http://idaas-admin.nmgyjtwg.org.cn/contacts/api/v1/departments/" + idaasDeptResponse.getId();
                                        String preSetOfficeStr = HttpUtils.httpGet(preSetOfficeUrl, bodyParam, headerParams);
                                        IDAASDeptResponse idaasDeptResponse2 = JSONObject.parseObject(preSetOfficeStr, IDAASDeptResponse.class);
                                        responseList.add(idaasDeptResponse2);
                                    }

                                    List<CsSystemOrgItemPreSetBean> offices = new ArrayList<>();
                                    if (!CollectionUtils.isEmpty(responseList)) {
                                        Map bodyParam2 = new HashMap();
                                        HashMap bodyParams2 = new HashMap<>();
                                        bodyParam2.put("status", new ArrayList<>());
                                        bodyParam2.put("identityClassification", "defaultIdentityClassification");
                                        bodyParams2.put("objectType", "USER");

                                        responseList.forEach(o -> {
                                                    if ("ENABLED".equals(o.getValues().getStatus())) {

                                                        CsSystemOrgItemPreSetBean office = new CsSystemOrgItemPreSetBean();
                                                        office.setMaxUserNumber(null == o.getValues().getMaxUserNumber() ? 20 : o.getValues().getMaxUserNumber());
                                                        office.setId(o.getId());
                                                        office.setName(o.getValues().getName());

                                                        List<String> orgId = new ArrayList<>();
                                                        orgId.add(o.getId());
                                                        bodyParam2.put("deptId", orgId);
                                                        bodyParams2.put("values", bodyParam2);


                                                        String url2 = "http://idaas-admin.nmgyjtwg.org.cn/api/v1/tn-3f90f739227e498bb3505237e6c397bb/objects/top_user/" + o.getId() + "/query?page_index=0&page_size=200&order_by=_udOrder&order_by=_displayName&need_child_depts=true";
                                                        String str2 = HttpUtils.sendHttpPost(url2, (JSONObject) JSON.toJSON(bodyParams2), headerParams2);

                                                        IDAASUserResponse object = JSONObject.parseObject(str2, IDAASUserResponse.class);
                                                        office.setUserNumber(object.getTotal());
                                                        // csSystemAdmin.setUserNumber(object.getTotal());
                                                        if (object.getTotal() > 0) {
                                                            office.setDeleteStatus(false);
                                                        }
                                                        offices.add(office);
                                                    }
                                                }
                                        );
                                    }
                                    preSetBean.setOrgChildren(offices);
                                }

                                if ("1000000012".equals(p) || "1000000014".equals(p)) {
                                    List<Object> data = new ArrayList<>();
                                    List<List<String>> data2 = new ArrayList<>();
                                    List<String> data3 = new ArrayList<>();
                                    CsSystemSourcePreSetInfo one = preSetInfoService.getOne(new LambdaQueryWrapper<CsSystemSourcePreSetInfo>().eq(CsSystemSourcePreSetInfo::getOrgId, csSystemAdmin.getOrgId()).eq(CsSystemSourcePreSetInfo::getSourceId, p).orderByDesc(CsSystemSourcePreSetInfo::getId).last("limit 1"));
                                    if (null != one && StringUtils.isNotEmpty(one.getPreSetTypes()))
                                        data = JSONObject.parseObject(one.getPreSetTypes(), List.class);
                                    if (!CollectionUtils.isEmpty(data)) {
                                        for (Object str : data) {
                                            List<String> list = Arrays.asList(str.toString().replace("\"[", "").replace("]\"", "").replace("[", "").replace("]", "").replace("\"", "").split(","));
                                            data2.add(list);
                                            if (null != list && !CollectionUtils.isEmpty(list)) {
                                                CsSystemSourceType sourceType = iCsSystemSourceTypeService.getById(list.get(list.size() - 1));
                                                if (null != sourceType) {
                                                    data3.add(sourceType.getName());
                                                }
                                            }
                                        }
                                    }
                                    preSetBean.setChildren(data2);
                                    preSetBean.setChildrenText(data3);
                                }

                                if ("1000002024".equals(p)){
                                    String phone = bean.getPhone();
                                    if (StrUtil.isNotEmpty(phone)){
                                        List<CsBusinessUser> csBusinessUserList = csBusinessUserService.findByPone(bean.getPhone());
                                        List<List<String>> data2 = new ArrayList<>();
                                        List<String> data3 = new ArrayList<>();
                                        for (CsBusinessUser cbu : csBusinessUserList){
                                            List<String> list1 = new ArrayList<>(2);
                                            list1.add(cbu.getParentBusinessId());
                                            list1.add(cbu.getBusinessId());
                                            data2.add(list1);
                                            data3.add(cbu.getParentBusinessName()+"-"+cbu.getBusinessName());
                                        }
                                        preSetBean.setChildren(data2);
                                        preSetBean .setChildrenText(data3);
                                    }

                                }
                                preSetBean.setId(p);
                                preSetOrgInfos.add(preSetBean);

                            }

                            csSystemAdmin.setPreSetOrgInfos(preSetOrgInfos);
                        }

                    }
                }
                if (null != idaasDeptResponse.getValues() && StringUtils.isNotEmpty(idaasDeptResponse.getValues().getRegionCode())) {
                    Area area = areaService.getById(StringUtils.rightPad(idaasDeptResponse.getValues().getRegionCode(), 12, "0"));
                    if (null != area) {
                        csSystemAdmin.setAreaCode(area.getId());
                        csSystemAdmin.setAreaName(area.getName());
                    }
                }

                if (StringUtils.isNotEmpty(bean.getOrgName())) {
                    if (idaasDeptResponse.getValues().getName().contains(bean.getOrgName())) {
                        if (StringUtils.isNotEmpty(bean.getName())) {
                            if (csSystemAdmin.getName().contains(bean.getName())) {
                                adminsAndDeptInfos.add(csSystemAdmin);
                            }
                        } else {
                            adminsAndDeptInfos.add(csSystemAdmin);
                        }
                    }
                } else {
                    if (StringUtils.isNotEmpty(bean.getName())) {
                        if (csSystemAdmin.getName().contains(bean.getName())) {
                            adminsAndDeptInfos.add(csSystemAdmin);
                        }
                    } else {
                        adminsAndDeptInfos.add(csSystemAdmin);
                    }
                }

                String[] areaMenus = {"1000000003", "1000000004", "1000000005"};
                List<String> areaMenusList = Arrays.asList(areaMenus);
                if (areaMenusList.contains(bean.getMenuID())) {
                    adminsAndDeptInfos.forEach(dept2 -> {
                        Area area = areaService.getById(dept2.getAreaCode());
                        if (null != area) {
                            //在国家行政区划表格没有的数据默认为认为创建的行政区划,可以删除,删除状态为 2
                            dept2.setCreateType("1");
                        }
                    });
                }
            }
        }
        return adminsAndDeptInfos;

    }

}





